Posted by: Cirilo Meggiolaro | 03/4/2009

Tip of the day #141 – Refactoring – Creating properties from class members

Visual Studio has some nice refactoring features as I described on Tip #4 and Tip #94. Today we are going to generate properties from class members with some clicks:

Let’s assume an existing code such as the following:

public class Foo
{
    public int _counter;

    public void FooMethod()
    {
        Console.WriteLine(_counter);
    }
}

public class Bar
{
    public void BarMethod()
    {
        Foo f = new Foo();
        f._counter = 20;
        f.FooMethod();
        f = null;
    }
}

It’s just a simple code but what if you had a large code with several methods and you had to encapsulate the class member in a property and change the calls of all methods to the new property?

How to…

To start, right click over the _counter variable and from the context menu select Refactor > Encapsulate Field as the following picture shows:

Picture 1 - The refactor context menu.

Picture 1 - The refactor context menu.

The Encapsulate Field screen is displayed:

Picture 2 - Encapsulate field

Picture 2 - Encapsulate field

Other option is to press ctrl + R, E to display the Encapsulate Field dialog;

Type the new property name;

Select an update reference options such as External that changes the code from external classes or All that replaces the class member with the property name everywhere;

Check the additional options that help on the preview and search.

Click OK. The code now must be similar to the following:

public class Foo
{
    private int _counter;

    public int Counter
    {
        get { return _counter; }
        set { _counter = value; }
    }

    public void FooMethod()
    {
        Console.WriteLine(_counter);
    }
}

public class Bar
{
    public void BarMethod()
    {
        Foo f = new Foo();
        f.Counter = 20;
        f.FooMethod();
        f = null;
    }
}


Responses

  1. I like that!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: