C# 3.0 : New Features

Implicitly Typed Local Variables

“Var” allows declaring a new variable of type var, whose type is implicitly inferred from the expression used to initialize the variable. Local variables can be declared as type var, Compiler does actually determine the actual type based on the data it is initialized.

It must be initialized in the same statement. The value that the variable is being initialized to determines the type of the variable.

var a = 3; –> a is created of type int

var str = “Priya” –> str is created of type string.

var a; (Gives error)  

 Usage of var  –> Used to store anonymous types as in LINQ based programming.  

var languageQuery = from one in Languages where one == “VC++” select new { one };

The part “new { one }” declares and instantiates an anonymous type.  Additionally the query probably returns a collection of that anonymous type. 

Implicitly typed arrays, on the other hand, are possible using a different syntax, as shown below:     

        var strArr = new[] {C, C++, C#}

The above line of code would end up declaring strArr as string[], we always know the type of the variable by looking at its declaration. They cannot be initialized to null and Cannot be used as Class members.

Anonymous Types

C# 3.0 gives the flexibility to create an instance of a class without having to write code for the class before hand as shown below.

new {nationality=”Indian”, hair =”Brown”, age=24

The above line of code, gives a new type that has three properties: nationality, skin, and age. Internally, the C# compiler would create a class that looks as follows, but it’s not accessible by application code.

class __Anonymous
{
private string _nationality = “Indian”;
private string _skin = ” White”;
private int _age = 24;
public string nationality {get { return _ nationality; } set { _ nationality = value;}}
public string hair {get { return _ hair; } set { _ hair = value; }}
public int age {get { return _ age; } set { _ age = value; }}
}

If another anonymous type, with the same sequence of names and types were created, then the compiler would create only a single anonymous type for both instances to use. Also, because the instances are, as you may have guessed, simply instances of the same class, they can be exchanged because the types are really the same.  

Now that we have a class, but still need something to hold an instance of the above class. This is where the “var” keyword comes in handy; it lets us hold a statically typed instance of the above instance of the anonymous type. Here is a rather simple and easy use of an anonymous type. 

 var priya = new {nationality=”black”, hair=” Brown“, age=24}

 

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 referrence types and are derived from ‘Object’ class. i.e. Anonymous types are automatically inferred and created from object initializers(An object initializer specifies values from one or more properties of an object. Which means one can specify a set of properties of an object through a series of assignments, such as {nationality=”Indian”, hair =”Brown”, age=24}, and an object is assigned these properties)

They have a method scope.

// example.cs

using System;
using System.Linq;
using System.Text;

namespace AnonymousTypes
{
class Program
{
static void Main(string[] args)
{
var priya = new {Nationality = “Indian”, Hair = “Brown”, Age = 24 };
Console.WriteLine(“Nationality = {0}\nHair = {1}\nAge = {2}”, priya. Nationality, priya. Hair, priya.Age);

Console.ReadLine();
}
}
}

 

 

 
 

 

 

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. This enables you to combine declaration and initialization in one step. public class coordinates
{
public int x;
public int y;
}

We can now go ahead and Declare & initialize a coordinates object using an object initializer, as shown below.

var mycoordinates = new coordinates { x=0; y=0 };

Also, we can easily give values to collections in a rather concise and compact manner in C# 3.0. For instance, the following C# 2.0 code:

List Flowers = new List();Flowers.Add(“Rose”);
Flowers.Add(“Sunflower”);
Flowers.Add(“Tulip”);
Flowers.Add(“Orchid”);

Now we can do it as

List Flowers = new List { “Rose”, “Sunflower”, “Tulip”, “Orchid” };

The default constructor gets executed before assigning the values.

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

Extension methods enable you to extend the existing types with additional static methods. Extension methods can be declared only in static classes and are identified by the keyword “this” as a modifier on the first parameter of the method. The following is an example of a valid extension method.

 

public static string getFirstTwoCharacters(this System.String st)
{
return st.Substring(0, 2);
}

Allows adding new methods to existing types without modifying the existing type. They are special kinds 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.
From within the extension method, you can’t access the private variables of the type you are extending.
Instance methods take precedence over extension methods in situations where they have same signature.

Lambda Expressions

 Lambda expressions are extension of anonymous methods introduced in C# 2.0. It enables you to declare your method code inline instead of with a delegate function.

It’s 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.

Let’s have a look at the following code.

class Demo
{
delegate void DelegateDemo();
static void Main(string[] args)
{
DelegateDemo myDelegate = new DelegateDemo(name);
myDelegate();
}
void name()
{
Console.Writeline(“Clara”) ;
}
}

In the above code, C# 1.x allowed you to write code blocks in methods, which can be invoked easily using delegates.

Now, Lets have a look at the same code using anonymous methods introduced in C# 2.0.

class Demo
{
delegate void DelegateDemo();
static void Main(string[] args)
{
DelegateDemo myDelegate = delegate()
{
Console.Writeline(“Clara”);
};
myDelegate();
}
}

After the delegate() is an anonymous method. Simpler compared to method based delegate invocation.

Now, Coming to Lambda expressions, it allows us to write anonymous methods in a more concise way as shown below. Lambda expression is written as a parameter list, followed by the => token, followed by an expression or statement block.

Rewriting the above code using Lambda expressions

class Demo
{
delegate void DelegateDemo();
static void Main(string[] args)
{
DelegateDemo myDelegate = () => Console.WriteLine(“Hiya!!”) ;
myDelegate();
}
}

Auto Implemented Properties

It simplifies the 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.

When a class is created, most of the times it is used only as a placeholder with getters and setters for holding property values without any additional logic.

Consider the following example.

public class Person
{
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; }
}
public string FullName
{
get { return FirstName + ” ” + LastName; }
}
}

From the above class declaration, it doesn’t contain any additional logic. The get and set properties are repetitive and they simply set or get the values of the properties without adding any value.

Now, coming to the Auto-Implemented properties, we can rewrite the above code as shown below.

public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return FirstName + ” ” + LastName;
}
private set {;}
}
}

In the above code, when you declare a property, the compiler automatically creates a private, anonymous field that is available only to the property’s get and set accessors.

The auto implemented properties must declare both a get and set accessors.

If you need to create a read-only property, modify the scope of the set accessor to be private.

Advertisements

One Response to C# 3.0 : New Features

  1. You should take part in a contest for one of the highest quality
    sites on the web. I most certainly will highly recommend this website!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: