.NET 3.5: Type Initializers sample

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

Based on few very simple examples, I will describe in this post some new features of .NET 3.5, which are fundamentals of the LINQ and everything beyond.
Imagine you have a class Customer with two fields:

public class Customer
{
  private string m_Name;

  public string Name
  {
    get { return m_Name; }
    set { m_Name = value; }
  }

  private string m_Address;

  public string Address
  {
    get { return m_Address; }
    set { m_Address = value; }
  }
}


Now, if it is required to initializes the instance of this class, you would have to create the instance and then set all required properties.
To avoid this procedure, the constructor has to be defined which initializes all required field: For example:

namespace Daenet
{
    class Customer 
    
{
       Customer (string address, string name) 
       {
         // Field initialization
       }
    }
}

Personally, I hate this, because it just takes too much time to type the code which is not well intellectual one. The good news is type initializers feature, which
does this job for you. Following example illustrates this feature:

namespace Daenet
{
    class Program 
    
{
       static void Main(string[] args) 
       {
          Customer c1 =
          new Customer { Name = "Damir Dobric", Address = "Derventa" };
         
          Customer
c2 = 
          new Customer { Name = "Stefan Aevermann", Address = "Maintal" };

          Customer
c3 =
          new Customer { Name = "Detlef Horn", Address = "Pforzheim" };
       }
    }
}


One more useful thing is that Visual Studio ORCAS provides a full intellisense support for this feature.


Posted May 28 2007, 11:30 PM by Damir Dobric
Filed under:

Comments

Damir Dobric Posts wrote .NET 3.5: Implicitly Typed Local Variables
on 05-28-2007 23:56

In this post I will show very short example which introduces the powerful feature of .NET 3.5 called

developers.de is a .Net Community Blog powered by daenet GmbH.