Partager via


C# 3.0 Features Basics For LINQ - PART 1

The 'var' Keyword

  1. Type inferred at compile time
  2. Can only be defined within method scope
  3. Mostly used when you need a variable for anonymous types which can only be resolved at compile time e.g. LINQ queries

Auto Implemented properties

This feature eases the creation of properties for a field inside the C# class e.g.

    1:  //C# 3.0 Code 
    2:  class Contact
    3:  {
    4:      public string Phone { get; set; }
    5:      public string Name { get; set; }
    6:  }
 In the above code, we create two properties.The compiler automatically creates a private variable here accessed only via getters and setters. 
In C# 2.0 we would write a considerably big code for achieving this : 
    1:  //C# 2.0 Code 
    2:  Class Contact { 
    3:   private string _name;
    4:   public String Name {
    5:      get {
    6:          If(_name != null )  {
    7:              return _name;
    8:          }
    9:      set {
   10:          _name = value;
   11:      }
   12:  }
  

Making Sense Of Object Initializers

In C# 3.0 you can use object initializers to assign values to accessible fields/properties at the time of object creation e.g.

    1:  // C# 3.0;Object initializer for our Contact class 
    2:  Contact myContact = new Contact { Phone = '1212', Name = 'Bindesh' }; 

This is useful when we want to use the anonymous types , since the only way to initialize them are using object initializers . It also helps in selecting a portion of the data that is needed from all the available data in an class e.g.

 

    1:  class Contact {
    2:      public string FirstName { get; set; }
    3:      public string LastName { get;set;}
    4:      public string  Email {get;set;}
    5:      public string Phone {get;set;}
    6:  }
    7:  var contact = from c in Contacts
    8:             select new { c.FirstName, c.LastName, c.Email } ;
Collection Initializers

As is the case with object initializers, you can also have the Collections initialized in a short way, like

    1:  //C# 3.0;Collections Initializer
    2:  List <Contact> contacts = new List <Contact> { 
    3:                                              {'Bindesh', 'Vijayan'},
    4:                                              {'Madhuban', 'Singh'},
    5:                                              {'Sukesh', 'A K'}
    6:                                           };

The same would have taken a considerable work in C# 2.0, e.g.

    1:  List<Contact> contacts = new List<Contact>();
    2:  //call Add each time for adding values
    3:  contacts.Add( new Contact('Bindesh', 'Vijayan'));

The collection initializer can work for all the types that meets the following criteria :

  • Implements IEnumerable interface
  • Has a public Add() method

Comments