Use regular expressions in Visual Studio to clean up code

Friday, February 20th, 2009 | .NET

This is a reminder to myself.

Knut, remember that Regular Expressions are very handy to clean up a lot of messy code.

Here is an example:
The following function call results in a code analysis warning:

DBHelper.SetPropertyFromDB(m_City, dr("CITY"))

It's a helper function that returns the typed value from a DBValue. Not really useful these days with NHibernate or Typed Datasets, but it's code from an old application. Here is the signature of the code:

Shared Sub SetPropertyFromDB(ByRef pProperty As Object, ByVal value As Object)

The warning reported is:

"Warning: Implicit conversion from 'Object' to 'String' in copying the value of 'ByRef' parameter 'pProperty' back to the matching argument."

To fix this, I created a new method that returns the correct typed value instead of returning the referenced parameter and marked the old method "Obsolete":

Public Shared Function GetDBValue(ByVal pProperty As Object, ByVal dbValue As Object) As Object

Now, I had to rewrite all the calls to the function (several hundred calls). This included returning the typed value into the same variable as the first parameter in the function call, like this:

m_City = DBHelper.GetDBValue(m_City, dr("CITY"))

This is easily achieved by using Regular Expressions in the "Find and Replace" dialog in Visual Studio:

Find What:

DBHelper.SetPropertyFromDB\({.*},

(note: the \ escapes the ( and the expression group is marked by a {})

Replace with:

\1 = DBHelper.GetDBValue(\1,

(note: the \1 will represent the expression group)

Pretty simple, and very powerful :-)

Tags: ,

No comments yet.

Leave a comment

Search

Knut Hamang

This is the official site for Knut Hamang. I am a professional technical consultant specialized in Microsoft and .NET technologies and platforms. I work as an independent consultant in Norway and have more than 10 years of professional experience. To get in contact with me, please send me an email or check my public profile on View Knut Hamang's profile on LinkedIn