Visual Studio has a build in Replace function that uses Regular Expressions. Let’s consider the following scenario:
Although it’s not “good” code many times a developer has to write the following code :
class Program { MyObj _currentObj = new MyObj(); void Bind(MyObj objToBind) { _currentObj.Name = objToBind.Name; _currentObj.Age = objToBind.Age; } } class MyObj { public string Name { get; set; } public int Age { get; set; } }
The part that I want to point out is the Bind method where we explicitly set the properties of _currentObj.
So far so good! But wait, a new requirement comes and “demands” to writer another method that does the opposite:
void ApplyValues(MyObj objToApply)
{
objToApply.Name = _currentObj.Name;
objToApply.Age = _currentObj.Age;
}
So what basically we did was to flip our statements. That’s OK for two properties but if you have 10? 20? or more? (well use reflection
) but if you must write it explicitly here is a Regex that will help you do it:
Find what:
{[^=]+}{=}{[^;]+}
Replace with:
\3\2\1
And here is a screenshot from the Replace window inside VS:
Be careful: Always replace in Selection to avoid possible mistakes. Also, there is a slight issue with spaces after you perform the replace but pressing Ctrl + K, Ctrl + D (formats the code) should solve it!
Use it and change it to fit your own needs!
Cheers!
Nikolaos Georgiou on said
Nice solution! I think every developer must have written this type of code, mapping a class from-and-to some other class (or some GUI controls for example).
djsolid on said
Thanks! That's true! It's almost inevitable...
vital on said
Interesting one.. shows the power of Regular Expression
ipplos on said
Nice!
Samprada on said
Nice tip! But I guess, you need to be a bit more careful while considering all possibilities for your regular expressions, before using it :-)