Sunday, November 14, 2010

.Net 3.5, C#, VB.Net Language Improvement: Automatic Properties, Object initializers, Collection Initializers, Lambda expression, Anonymous type.

The new .net 3.5 has significant improved features. This feature makes the .net programming concept more sophisticated. You will now be able to write less code and build more dynamic application using those.

From all of them what the most I like is the LINQ, which allow you to query over variety of objects.

LINQ is all about queries, they returns a set of matching objects, a single object, or a subset of fields from an object or set of objects. In LINQ, this returned set of objects is called a sequence.

Basically LINQ comes in variety of flavors' like following:

  • LINQ to Objects
  • LINQ to XML
  • LINQ to Dataset
  • LINQ to SQL
  • LINQ to Entities

Well there is a detailed discussion on LINQ further in this article. Let me first make you guys introduce to the language improvements in .net 3.5. In fact I believe that these new improvements are essential to learn before we actually get dig into the LINQ J.

To summarize quickly, here are the list of new language feature that are shipped with .Net 3.5.

  • Automatic properties
  • Object initializers, Collection initializers
  • Anonymous types
  • Extension methods
  • Query Expression

Well if you are the C# developer, I believe you will really love to have such significant improvement. Because these features puts extra wing on your programming skill.

The important is not that you learn the latest technology of .Net 3.5 like WCF, WPF, Silverlight etc. These are the core part of basic programming. Its like you should be knowing the if syntax of C programming language before you actually write your first "Hello word" program J

So let's go through each of them step by step and try to understand what they are and how it can help the developer to create rich internet/desktop application.

  • Automatic Property

Before I explain you the concept of "automatic property in .net 3.5, can you guys first please try to go through the following code?

public
class
MShoppingCart

{


private
int _cartId;


public
int CartId

{


get { return _cartId; }


set { _cartId = value; }

}


private
int _customerid;


public
int Customerid

{


get { return _customerid; }


set { _customerid = value; }

}


private
int _billingaddressid;


public
int Billingaddressid

{


get { return _billingaddressid; }


set { _billingaddressid = value; }

}


private
int _shippingaddressid;


public
int Shippingaddressid

{


get { return _shippingaddressid; }


set { _shippingaddressid = value; }

}


private
MShippingCartItem _cartitem;


public
MShippingCartItem Cartitem

{


get { return _cartitem; }


set { _cartitem = value; }

}

}

Most of the time we are used to write such model classes. This are the most basic and popular mechanism in returning a wrapper classes. The basic purpose of writing such getter/setter property is to hide the actual private member of our classes. It has been the standard pattern to access the private method of any classes. Well you may arise with a question that why do we actually need to write such getter/setter properties. Can't we simply expose the private member? Well the answer is YES, but I would request you to remember the fundamental of object oriented programming. J

Anyway there are basically two reason of not doing so. Following are this:

  1. You won't be easily able to bind those private variable to controls
  2. You will not be able to modify them into property later on.

The first point is quite understandable, what do you mean by the second one? Well, say for e.g. if you need to add any business logic or validation logic when assigning value to any private variable then? You will not be able to do that.

So what if we need not to write even the private variables? Exited, yes the new version of .Net 3.5 allows you have such facility. The concept is called automatic property. All you have to do is to write the getter/setter property. You need not to worry about the private member of that property. The compiler will decide and prepare base private member for you on the fly.

See the example in the following.

public
class
MShoppingCart

{


public
int CartId

{


get;


set;

}


public
int Customerid

{


get;


set;

}


public
int Billingaddressid

{


get;


set;

}


public
int Shippingaddressid

{


get;


set;

}


private
MShippingCartItem _cartitem;


public
MShippingCartItem Cartitem

{


get;


set;

}

}

Now it this case when the compiler will encounter this properties while compiling your code, it will automatically expose the private variable for each of property with its associated type. For e.g. compiler automatically assume and expose the _cartid private variable of integer type. Using advantage of this is we need not to worry about the underlying private variable. In future we can add any sort of validation logic in this property.

  • Object initialization, collection initialization

I would like to explain this concept by taking the example of automatic property so that I maintain the continuity for you to understand. Say for e.g. when we want to use the "shopping cart" class that we created earlier. What we do is write following code.

MShoppingCart cart = new
MShoppingCart();

cart.CartId = 1;

cart.Customerid = 1001111;

cart.Shippingaddressid = 2333;

cart.Billingaddressid = 2232;

With the feature supported by the .net framework 3.5, you can take advantage of what is called "syntactic sugar", and that is object initializers.

Using object initializers, you can write the same code given above, in following way.

MShoppingCart cart = new
MShoppingCart {CartId =1, Customerid=1001111, Billingaddressid=2232, Shippingaddressid =23333 };

So it allows you to pass the value of all property at the time of initializing the object.

In fact it not only allow to initialize object's property in this way, you can also have nested initialization of object within any object.

To demonstrate you, see the following example.

MShoppingCart cart = new
MShoppingCart { CartId = 1, Customerid = 1001111, Billingaddressid = 2232, Shippingaddressid = 23333, Cartitem = new
MShippingCartItem { }
};

If you see in the highlighted (underlined) part of above code, you can clearly see that the child object can also be initialized in the same way.

As if the new object initialization enhancements were not enough, someone at Microsoft must have said, "What about collections?" Collection initialization allows you to specify the initialization values for a collection, just like you would do for an object, as long as the collection implements the

System.Collections.Generic.ICollection<T> interface.

List<string> presidents = new
List<string> { "Name 1″, "Name 2″, "Name 3″ };

foreach (string president in presidents)

{

Console.WriteLine(president);

}

  • Anonymous types

What is anonymous type?

Well, we have been familiar till date with different types. They are either custom classes or any of .net's build in type. So what is actually the anonymous type is. The answer is that the "Anonymous type" has no type defined to it. It has no type name. Though there should be at least one type name associated in .Net. In anonymous type, the type name is specified by the developer doing the programming. It is the compiler which will identify the type to associate with the declaration of any anonymous type.

There is also another significant different in anonymous type is that it is called immutable. The definition of immutable type is that the one that is declared and initialized once. It can't be altered later on. So anonymous type has the same characteristic. Once you declared and initialized, you can't alter the anonymous type afterward.

This is also why anonymous types have been introduced. They allow us to create a type on the fly and therefore return only certain values of a given named type. This is very handy when only a subset of properties is needed, properties are joined together or even objects are joined together.

class
Program

{


static
void Main(string[] args)

{


// create a list of carts with dummy data.


List<MShoppingCart> carts = new
List<MShoppingCart>();

carts.Add(new
MShoppingCart { CartId=101, Customerid=1001, Billingaddressid=20, Shippingaddressid =30});

carts.Add(new
MShoppingCart { CartId = 102, Customerid = 1002, Billingaddressid = 22, Shippingaddressid = 33 });

carts.Add(new
MShoppingCart { CartId=103, Customerid=1003, Billingaddressid=23, Shippingaddressid =34});


// query the cart collection to collect cart with id of 101


var result = from c in carts


where c.CartId >= 101


// put the result in a anonymous type


select
new { c.Billingaddressid };


// loop over the result.


foreach (var item in result)

{


// print out the name of the item.


Console.WriteLine(item.Billingaddressid );

}

}

}

Anonymous type are mostly used when working with the LINQ. It is utilized highly while querying to your data in LINQ. It is irrespective which flavor of LINQ you are using.

Although the anonymous type can be used in your own code also. It is especially useful when we want to combine different variables into one.

Se for e.g. following example:

// create an anonymous type instance with a name.


var anonymousType = new

{

Name = name,

Age = age,

Nationality = nationality

};


// print the name to the console.


Console.WriteLine(anonymousType.Name);

Though the real time use of anonymous type Is when you use it with the LINQ. I need to write a separate article to demonstrate you actual usage LINQ. J

  • Extension methods

An extension method is a static method of a static class that you can call as though it were an instance method of a different class.

To make you understand the extension method, let me first re cape the class level methods (static methods) and instance methods. The primary different between these two is that the instance method can also be access by initializing object of any class. It can't be invoked by using class name only. The exact opposite of that is class method. You can only call static class method using the name of class only. You can't access them using the instance of same class.

I am not gonna give you any example for the above explanation as I expect from you guys that you are familiar with the different I explained.

Extension method is a way of extending existing classes for whatever additional functionality. Let me demonstrate you that by example.

namespace ExtensionMethods

{


public
static
class
StringExtensionMethods

{


public
static
bool IsNumeric(this
string str)

{


try

{


int i = int.Parse(str);


return
true;

}


catch

{

}


return
false;

}

}

}

In the above given example, almost everything seems to be similar what we are used to in normal programming. But, the difference is clearly seen. You should be able to notice that in the "IsNumeric" static method parameter are passed using this keyword. This keyword tells the compiler what you are going to extend for particular given type. So in this example it tells you that it extends the existing string class.

See for e.g. how to use the extension method.

string s = "someValue";


bool bs = s.IsNumeric();


// bs is false;


string i = "7″;


bool bi = i.IsNumeric();


// bi is true;

  • Query Expression

One of the conveniences that the C# language provides is the foreach statement. When you use foreach, the compiler translates it into a loop with calls to and MoveNext. The simplicity the foreach statement provides for enumerating through arrays and collections has made it very popular and often used.

One of the features of LINQ that seems to attract developers is the SQL-like syntax available for LINQ queries. The first few LINQ examples in the first chapter of this book use this syntax. This syntax is provided via the new C# 3.0 language enhancement known as query expressions. Query expressions allow LINQ queries to be expressed in nearly SQL form. To perform a LINQ query, it is not required to use query expressions. The alternative is to use standard C# dot notation, calling methods on objects and classes.

Although it is occupy a dedicated book for detail understanding of query expression with LINQ. Just to summarize you, here is the example that shows you what actually query expression does.

For e.g.

string[] names = {

"Adams", "Arthur", "Buchanan", "Bush", "Carter", "Cleveland",

"Clinton", "Coolidge", "Eisenhower", "Fillmore", "Ford", "Garfield",

"Grant", "Harding", "Harrison", "Hayes", "Hoover", "Jackson",

"Jefferson", "Johnson", "Kennedy", "Lincoln", "Madison", "McKinley",

"Monroe", "Nixon", "Pierce", "Polk", "Reagan", "Roosevelt", "Taft",

"Taylor", "Truman", "Tyler", "Van Buren", "Washington", "Wilson"};

IEnumerable<string> sequence = from n in names


where n.Length < 6


select n;


foreach (string name in sequence)

{


Console.WriteLine("{0}", name);

}

Though query expression can be used by two different way. 1) is using dot notation and 2) is using expression syntax.

Hope I could make you understand what are the new improvements in the newer version of .net 3.5.

Once you are aware and familiar with this feature, you are ready to get dig into dip into the word of .net 3.5 for all new existing experience in developing rich internet/enterprise application.

 

No comments: