Saturday 23 April 2011

Automatic Properties, Object Initializers and Collection Initializers

Introduction

In c# 3.0 and later versions many new features are available but some people are not aware of them. There are some new features explained below In C# 3.0 and later.

Auto-implemented properties:

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

Let’s see the old writing method.
public class Person
{
 private string _firstName;
 private string _lastName;
 private int _age;
 
 public string FirstName
 {
  get
  { return _firstName; }
 
  set
  { _firstName = value; }
 }
 
 public string LastName
 {
  get
  { return _lastName; }
 
  set
  { _lastName = value; }
 }
 
 public int Age
 {
  get
  { return _age; }
 
  set
  { _age = value; }
 }
}
Now we can see the enhanced implementation.

public class Person
{
 public string FirstName
 {
  get;
  set;
 }
 
 public string LastName
 {
  get;
  set;
 }
 
 public int Age
 {
  get;
  set;
 }
}
Note: This way is possible only when you don’t want to write any logical implementation in the getter/setter part. If you want to write implementation then you must go through the old method.

Object & Collection Initializers:

Object/Collection initializers, let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

Considering above example now we initialize of an object with the old method.

Person person1 = new Person();
person1.FirstName = "Munavvar";
person1.LastName = "Husein";
person1.Age = 25;
Now in place of this we can write it like,

Person person1 = new Person
{
 FirstName = "Munavvar",
 LastName = "Husein",
 Age = 25
};

In the case of Collections same thing would be done as under. Considering above examle to make a list with old method.

List<Person> lstPerson = new List<Person>();
 
Person persons = new Person();
persons.FirstName = "Munavvar";
persons.LastName = "Husein";
persons.Age = 25;
lstPerson.Add(persons);
 
persons = new Person();
persons.FirstName = "Rikin";
persons.LastName = "Patel";
persons.Age = 26;
lstPerson.Add(persons);

Now in place of this we can write it like,

List<Person> lstPerson = new List<Person>;
{
 new Person
 {
  FirstName = "Munavvar",
  LastName = "Husein",
  Age = 25
 },
 
 new Person
 {
  FirstName = "Rikin",
  LastName = "Patel",
  Age = 26
 }
};
Conclusion:
As per enhanced feature we can just reduse the burdon of typing extra statements with no loss of performance.

No comments:

Post a Comment