Wednesday, March 28, 2012

Object Initializers

With the help of Object Initializers, you can initialize objects with fewer lines of code.

For. e.g:

We have a class representing a Student.


public class Student
    {
        public string StudentName;        
        public int StudentID;

        public Student(string StudentName, int StudentID)
        {
            this.StudentName = StudentName;
            this.StudentID = StudentID;
        }

        public Student(int StudentID)
        {            
            this.StudentID = StudentID;            
        }

        public Student()
        {
        }
    }

Suppose we make a class for Student List and inherit it from class List. To add objects to this class, we'll make use of object initialization.

Before we had object initialization, we would have had to do the following:


public void Add(string StudentName, int StudentID)
 {
     Student std = new Student(StudentName, StudentID);
     this.Add(std);
 }
 
With object initialization, the code can be reduced to the following lines: 


public void Add(string StudentName, int StudentID)
{
    this.Add(new Student { StudentID = StudentID, StudentName = StudentName});
}
 
Do note that the resulting IL Code of both the above code snippets will be the same. However, you can see the difference in the lines of code the developer will need to type. Though, this may not sound very beneficial by looking at the above example. But try implementing object initialization in real-life code and you'll see the benefit.


The above example used object initialization without constructor. Here's how you use it with constructor.



public void AddStudent2(string StudentName, int StudentID)
{
   this.Add(new Student(StudentName, StudentID));
}
 
Another way to use object initialization is by calling the constructor and initializing the properties at the same time:
 
public void AddStudent(string StudentName, int StudentID)
{
    this.Add(new Student(StudentID) { StudentName = StudentName });
}

Saturday, March 24, 2012

Implicitly Typed Local Variables (C#)

While coding, at some point, you might want to be able to declare a variable without having to explicitly mention the type of this variable.
C# 3.0 allows this by introducing a keyword var.

Here's how you use it:

var i = 0;
var str = "some string";
 
The type of the variable is deduced by the statement at the right hand side. However, these variables are still not loosely typed. You can check this be assigning different type of values to the same variable. For e.g., the variable i above cannot later on be assigned a string value.

The code below;

var i = 0;
i = "some string";

would give a compile-time error ("Cannot implicitly convert type 'string' to 'int' ").

Though, the use of implicitly typed variables may not be understandable by just these examples, these are really helpful when you are using LINQ.

References: