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

Anonymous 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 TRILLES said…
Nice input . ....

Popular posts from this blog

Getting Started with Stateless : A Lightweight Workflow Library Alternative for .NET

Image Credit: https://www.pioneerrx.com A year ago, I was looking for a simple workflow manager for a project I was working. Its a medium sized application that involves tracking the state of assets in the system. Back in 2008, Microsoft (MS) introduced new technologies along with the release of Visual Studio 2008: Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), and  Windows Workflow Foundation (WF). Having worked in a company utilizing mostly MS products for development, my first option was to go with WF. After doing some time reading and studying the library, I paused and decided it was too complex for my requirement. Using WF would be an overkill and the fact that it has, a rather, steep learning curve, there has to be another option. My mind toyed with the idea of developing a simple workflow library myself. It would be a learning experience but it might end up consuming a lot of time. Why reinvent the wheel? So I started querying the inte

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

Cyber-bullying : The "good", the bad and the ugly

Image courtesy of http://www.digitalesq.com/ Cyber-bullying is defined as  the willful and repeated use of cell phones, computers, and other electronic communication devices to harass and threaten others. With the advent of social media, the incidents has increased in numbers and the victims does not even know what is hitting them. For the past years, we have heard of  depressions and deaths because of this. Yet, there has never been a strong drive to increase public awareness and promote support groups to help victims outside of the schools.  Campaigns and programs has never gained mainstream presence enough to make an impact.