Monday, March 29, 2010

C# Language

1. Implicit Typed Local Variables


Declaring variable without specifying data-type.
E.g. var count = 1 ; instead of int count = 1;
E.g. var str = "Hello World"; instead of string str = "Hello World";
- var is not like an object or a variant type that has expensive cost.

- The compiler will set the data-type depending on what you initialize the variable.

Usage of Type Inference


- You can use it When deal with Anonymous type in LINQ.
- Declaration must include an initializer.
e.g. var test = "Hello World";

- Initializer must be an expression and not an object or collection initializer and also can not initialize it with an array.
e.g. var test = {1,2,3} ; //Gives error

- Compile time type of the initialzer expression can not be the null type.
e.g. var test = null;

- Implicity typed local variable can be initialize more than once but not with different type.
e.g. var test = 1;
test = "Hello World";

Benefits of Type Inference


- Save the typing time.
- It induces/brings on variable initialization

Limitations


- Scope is limited to local variable

2. Auto Implemented Properties


A way to declare property without code block in property accessors.

Usage of Auto Implemented Properties


- We can use it in data-accessor classes.

Note: VB 9.0 does not have auto implemented properties feature while C# 3.0 have.

- It makes property declaration more concise when there is no custom logic required in property accessors.

For example,
Suppose we have to create a class Employee with private attributes First-Name, Last-Name and ID. Now in order to access its attributes values either we can create properties or functions for each attribute.

In C# 2.0, we implement Employee class with above requirements as follows

 
public class Employee
{
 int _id;
 string _firstName;
 string _lastName;
 public int ID
 {
  get
  {
   return _id;
  } 
  set
  {
   _id = value;
  }
 }
public string FirstName
 {
  get
  {
   return _firstName;
  } 
  set
  {
   _firstName = value;
  }
 }
public string LastName
 {
  get
  {
   return _lastName;
  } 
  set
  {
   _lastName = value;
  }
 }
}


In C# 3.0, we implement Employee class with few lines for above requirements.

public class Employee
{
 public int ID
 {
  get;
  set;
 }
public string FirstName
 {
  set; 
  get;
  
 }
public string LastName
 {
  get;
  set;
 }

}


How to create read-only property?


We can create read-only property by adding private keyword private before set.
e.g.
public class Employee
{
 public int ID
 {
  get;
  private set;
        }
}


How to initialize read-only property?


public class Employee
{

 public Employee(int ID)
 {
  this.ID = ID;
 }
  
public int ID
 {
  get;
  private set;
        }
}


You can not create write only auto implemented properties but you can create it by traditional way.


public int ID
{
 set
 {
  _id = value;
        }
}


Benefits of Auto Implemented Properties


- Save typing time
- Increase productivity

3. Anonymous Types


A way to encapsulate a set of read-only properties into a object without defining class explicitly.

- The compiler will define a type/class automatically that represents the Anonymous Types in background.

- Anonymous types have been created with the help of "Object initializers" and implicitly typed variables.

- The Anonymous type is created with read-only properties mean you can not assign values to it after creation.

- It is strongly type.

- Mutable in VB and immutable in C#.

For example,
var product = new {Name = "C# Rocks!", Price = 3};

Automatically gets translated by the compiler to something like this:

class __Anonymous1
{
   private string name;
   private int price;

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

   public int Price
   {
      get { return price; }
      set { price = value; }
   }
}

__Anonymous1 product = new __Anonymous1();
product.Name = "C# Rocks!";
product.Price = 3;


Usage of Anonymous Types


- Use anonymous types when you deal with Linq to store query results. Anonymous type can be used in "LINQ to SQL" to access some of the fields from a whole set of fields.

Limitations of Anonymous Types


- The scope of Anonymous type is limited to the method in which it defines.

- It can not be used in method parameters or return values, class level (global) variables, properties.

4. Extension Methods


A way to extend an existing type
For example,
public static class StringExntensionMethods
    {
        public static void AlertMessageBox(this string str)
        {
            MessageBox.Show(str);
        }
   }
string str = "Extesion Method Example";
str.AlertMessageBox();


Benefits of Extension Methods


- To extend an existing type.
- To specify validation on value of an existing type instance.

5. Object and Collection Initializers


A way to initialize accessible members of a class at object creation time without invoking constructor explicitly.

For example,
class Employee
{
    // Auto-implemented properties
    public int Age { get; set; }
    public string Name { get; set; }
}

 // Object initializer
 Employee obj = new Employee {Age = 24, Name = "Test"};

public class CoOrdinate
{
   public int x ;
   public int y;
}


Now we can create and initialize the object via this.

var myCoOrd = new CoOrdinate{ x = 0, y= 0} ;

The above code can also be replaced by creating constructor with arguments Age and Name. Then what is the benefit of Object Initializers? The benefit here is that the arguments order and the number of arguments.


- Collection initializers allow to specify one or more element initializers when you create an object of collection class that implements IEnumerable.(i.e. Element initializers can be a simple value, an expression or an object initializers.)

In C# 2.0, we create collection and add elements in collection.
For example,

List animals = new List();
animals.Add("monkey");
animals.Add("donkey");
animals.Add("cow");
animals.Add("dog");
animals.Add("cat");


In C# 3.0, the above code will be replaced by collection initializers features in C# 3.0

List animals = new List {
"monkey", "donkey", "cow", "dog", "cat" } ;

//Element initializers as a simple value
List digits = new List { 0, 1, 2 };

//Element initializers as a Object initializers
List emp = new List { new Employee(1), new Employee{FirstName = "Test", LastName = "Test" } };

Benefits of Object and Collection Initializer


- The benefit of object initializers is that the arguments order and the number of arguments.

6. Lambda Expressions


It is a substitution for anonymous method – declaring method inline.

For example,
1) Traditional way of assigning method to delegate

delegate bool SomeDelegate(int i);
public void SomeMethod()
{
 SomeDelegate sd = new SomeDelegate(OtherMethod);
}
private bool OtherMethod(int i)
{
   return i > 2;
}

2) Replacing traditional way of declaring method and then assign it to delegate by declaring method inline via anonymous method.
delegate bool SomeDelegate(int i);
private void SomeMethod()
{
 SomeDelegate sd = delegate(int i){return i > 2;}
}

3) Replacing anonymous method using Lambda Expression
delegate bool SomeDelegate(int i);
private void SomeMethod()
{
 SomeDelegate sd = (int i) => { return i > 2;}

}


Benefits of Lambda Expressions


- Save typing time via minimal syntax - write inline code block where delegates are expected. No need to specify return types and name explicitly.
- It provides support for expression tree.

Usage of Lambda Expressions


- Replacement of Anonymous Methods.
- It can be also be used for filtering, sorting, iterating in generic collection and LINQ.