Skip to main content

Automatic Properties and Object Initializers in .Net 3.5

With the release of .Net 3.5 alongside with Visual Studio 2008 , new enhancements was again introduced . Some maybe well pronounced such as the inclusion of WCF, WPF , LINQ in .Net 3.0 and some just came unnoticed. If you have been accustomed of using a particular method or technique in implementing a certain code in .Net 2.0 , because of backward compatibility , you may not even notice that there are new ways of implementing it in .Net 3.5.

Here are two new concepts in .Net 3.5 that a developer may not notice ( at least in my opinion ) : Automatic Properties and Object Initializers . To illustrate these two , I am going to present the pre-.Net 3.5 way (.Net 2.0) and the .Net 3.5 way in creating a simple class with simple properties.

Automatic Properties

Creating a class can be tedious , especially when working with a list of properties , . One way to get around having to type the code for a private field and its public property getter and setter is to use a refactoring tool. However, there is a new language feature called Automatic Properties that allows you to type less code and still get a private field and its public getter and setter. You declare the automatic property using a shortcut syntax and the compiler will generate the private field and the public setter and getter for you.

.NET 2.0 Way

To build a simple class with two properties (i.e. FirstNumber and SecondNumber) and a method (i.e. GetSum()) , you write a code similar below:

public class OldSimpleMath
{
   private int _firstNumber;
   private int _secondNumber;
   public OldSimpleMath()
   {
   }
   public OldSimpleMath(
        int firstNumber,
        int secondNumber)
   {
        _firstNumber = firstNumber;
        _secondNumber = secondNumber;
   }
   public int FirstNumber
   {
        get { return _firstNumber; }
        set { _firstNumber = value; }
   }
   public int SecondNumber
   {
        get { return _secondNumber; }
        set { _secondNumber = value; }
   }
   public int GetSum()
   {
        return _firstNumber + _secondNumber;     
   }
}


Notice the use of two constructors to enable overloading.

.Net 3.5 Way

In .Net 3.5 , using the new feature , this would only give us a code similar below:

public class SimpleMath
{
   public int FirstNumber
   {
        get;
        set;
   }
   public int SecondNumber
   {
        get;
        set;
   }
   public int GetSum()
   {
        return FirstNumber + SecondNumber;
   }
}


Notice that there are no longer private variables to hold a local copy of our data , .NET 3.5 will take care of that. A constructor was not even defined . And yes , the class definition is much much simpler that in .Net 2.0.

If you are using VS2008 , make sure that the targetframework is set to .Net 3.5 , otherwise you will be generating compile errors.

Object Initializers

Object Initializers allow you to pass in named values for each of the public properties that will then be used to initialize the object.

.NET 2.0 Way

Notice our class using the old .Net 2.0 way above , it has two constructors . One accepts no parameters , while the other accepts two integers . Imagine that you have more than two properties that you want to initialize upon instantiation and with different possible combinations . That would take you time to code right?

In the pre .Net 3.5 era , you will write this codes to use the OldSimpleMath class:

static void UsingOldWay()
{
   OldSimpleMath number=
        new OldSimpleMath();
   number.FirstNumber = 1;
   number.SecondNumber = 5;
   Console.WriteLine(number.GetSum());
   //using constructor
   OldSimpleMath newNumber=
        new OldSimpleMath(5,8);
   Console.WriteLine(newNumber.GetSum());
}


Using a constructor that was not implemented in the class would generate compile errors.

.Net 3.5 Way

With object initializers , we can have a dynamic form of constructors . The syntax is to wrap the named parameters and their values with curly braces. Object Initializers allow you to pass in any named public property to the constructor of the class. This is a great feature as it removes the need to create multiple overloaded constructors using different parameter lists to achieve the same goal. While you can currently create your own constructors, Object initializers are nice because you do not have to create multiple overloaded constructors to handle the various combinations of how you might want to initialize the object. To make matters easier, when typing the named parameters the intellisense feature of the IDE will display a list of the named parameters for you. You do not have to pass all of the parameters in and in fact, you can even use a nested object initialize for a certain parameter.

static void UsingNewWay()
{
   SimpleMath number =
        new SimpleMath();
   number.FirstNumber = 4;
   number.SecondNumber = 5;
   Console.WriteLine(number.GetSum());
   //using object initializer
   SimpleMath newNumber =
        new SimpleMath
        {
            FirstNumber=2,
            SecondNumber=4
        };
   Console.WriteLine(newNumber.GetSum());
}


Nice new feature right? It reduces a lot of coding time and allows you to concentrate more on the actual logic of the program.

Note: If you are using Resharper 3.1 for VS2008 , the version does not pick up these new features so you can see that they are flagged as errors by Resharper and in some cases for the Object Initializers the intellisense may not work . None the less , if you are sure that your creating a .Net 3.5 project , just hit the build button and everything will just be fine.

Comments

Jon Limjap said…
You could also use the var keyword:

var newNumber =

new SimpleMath

{

FirstNumber=2,

SecondNumber=4

};

You can also uprgrade your Resharper to version 4.0, which updates Resharper to the C# 3.0 spec :)
Marvin said…
Nice input . ....
This kind of information is very limited on internet. Nice to find the post related to my searching criteria. Your updated and informative post will be appreciated by blog loving people.

Dissertation writing advice

Popular posts from this blog

Hiding Unwanted Python Folders and Files in Visual Studio Code

Visual Studio Code is a universal editor and pretty good at it. However, the explorer view maybe cluttered with the automatically generated folders and files confusing developers. Python is no different. Below are example files and folders generated by Python.

The __pycache__ folder and *.pyc files  are totally unnecessary to the developer. To hide these files from the explorer view, we need to edit the settings.json for VSCode. Add the folder and the files as shown below:
Copy and paste the lines below :

"**/*.pyc":{"when":"$(basename).py"},"**/__pycache__":true

renaming default namespaces for VSTO projects in VS2008

So here is the scenario , you are starting a VSTO project and decided that your default namespace is ExcelAddInTesterApp . You created the project and started coding the project. After several days , your boss called and said "hey marvin , make use of this namespace OurCompany.ExcelAddInTesterApp , we have to add our company name to it got it?" . You get back to your machine thinking its just a simple property just like any project you've been working on. So you right clicked the VSTO project and hit properties . Boom! What the F@#$? The default namespace textbox is disabled!!!!



I've been through this and I googled for ways to do it and ended up with a blog from a Microsoft MVP telling me it can't be done because it is disabled. Then I thought of Refactoring, the beauty and grandeur of the renaming process. I selected the namespace and hit the refactor menu hoping that this would solve the problem . Unfortunately , it did not rather it displayed the message box …