What's New in CSharp 3.0
Implicitly Typed Local Variables
Local variables can be declared as type ‘var’ which means compiler to determine the actual type based on the data by which its is initialized.
var i = 10; // i is created of type int
var name = “MyName” ; // name is created of type string
can only be used when declared and initialized in same statement.
Cannot be initialized to null.
Cannot be used as class members.
Mostly used to store anonymous types as in LINQ based programming.
Object & Collection Initializers
Allow assigning values to any accessible members or properties of a type at the time of initiation without invoking the constructor with parameters.
The default constructor gets executed before assigning the values.
E.g. Coordinate c1 = new Coordinate {x=1 , y=2};
Used in LINQ query expressions along with anonymous types.
Collection Initializers use Object Initializers to specify multiple elements of collection without calling Add method multiple times.
Extension Methods
Allows adding new methods to existing types without modifying the existing type.
Are special kind of static methods but are called as if they are instance methods.
The first parameter passed to Extension methods specifies to which type they operate on preceded by ‘this’ keyword.
They cannot access the private variables of type which they are extending.
Extension Methods need to defined in a non-nested and non-generic static class.
Instance methods take priority over extension methods in case they have same signature.
Anonymous Types
Are of class types which can have only public read-only properties as their members. No other class members like methods are allowed.
They are of reference types and are derived from ‘Object’ class.
Internally compiler gives them the name but its not accessible by application code.
They have a method scope.
Can be initiated directly e.g. new { property1=1, property2=”Hello World”};
Lambda Expressions
Very similar to anonymous methods introduced in C# 2.0.
Its an inline expression or statement block which can be used to pass arguments to method call or assign value to delegate.
All lambda expression use lambda operator => where the left side denotes result and right contains statement block or expression.
Auto-Implemented Properties
Helps in simplifying property declaration in cases where there is no custom logic required in accessors methods.
E.g. public int Price {get; set;};
Internally compiler creates an anonymous field for assigning values.
In my next post on this i will demonstrate these using a code sample.
Thursday, January 29, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment