Visual Studio - A Common Replace Scenario

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 Smile with tongue out) but if you must write it explicitly here is a Regex that will help you do it:

Find what:

Replace with:

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!



Add a Comment (gravatar-enabled)