Visual studio and .NET tip 5:- Encapsulate public properties with a single click
By Shivprasad Koirala
Many times due to project pressure and lazy attitude you violate encapsulation and create public variables for classes as shown below. Even though your inner heart knows that the best practice is to create set and get property function but your lazy attitude overrules it.
Visual studio and .NET tip 5:- Encapsulate public properties with a single click
Many times due to project pressure and lazy attitude you violate encapsulation and
create public variables for classes as shown below. Even though your inner heart
knows that the best practice is to create set and get property function but your
lazy attitude overrules it.
public class Supplier
{
public string supplierCode;
}
So you can keep your lazy attitude and also implement encapsulation by using encapsulate
field from the refactor menu. So select your public variable, right click, go
to refactor menu and click on encapsulate field as shown in the below figure.

It then pops up dialog boxes for property names and also helps your preview the code
changes. Once you apply it you should get the below line of code with public
properties and private encapsulated fields.
public class Supplier
{
private string supplierCode;
public string SupplierCode
{
get { return supplierCode; }
set { supplierCode = value; }
}
}
Related FAQs
When we select source code in visual studio it selects the complete source code , but what if we want to select the code in a rectangular manner?
In this section we will see a very interesting and useful trick of visual studio called the extract method.
Now many times as a .NET developer we need connection strings to connect to databases. Connection string are long and cryptic and very difficult to remember. In this tip we will see a easy way of getting connection strings.
Many times we write comments in code to remind about certain tasks to be performed later and then we forget about the same as the comments gets lost in those million lines code.
While debugging you often want to skip debugging on certain lines of code. For instance in the below code you have set the debug point to the first line, you would like to skip the in between lines and jump directly to “console.writeline” step.
As a developer you always need some common codes again and again. Rather than writing those common codes from scratch you would like to get them easily from some handy place.
Visual studio and .NET tip 5:- Encapsulate public properties with a single click (725 Views)