Wednesday, April 1, 2009

Implicitly Typed Variable – Features of C# 3.0 (Part - 3)

In my previous blog we had a look at Automatic properties in C# 3.0. In this blog we will try to understand what implicitly typed variables are? To know more read on.

What is Implicitly Typed Variables?

In our day to day C# programming we declare variables something like this.

int i = 6;
string name = "Sandeep";

We have to first specify what is the data type and then the initial value for the variable. With C# 3.0 you need not specify the data type, instead you can make use of the “var” keyword. The above code can be rewritten as shown below.

var i = 6;
var name = “Sandeep”;

Using the “var” keyword will tell the C# compiler to infer the data type of the variable from the initial value supplied. One thing to note here is that if you don’t provide an initial value the system will throw the following error.

“Implicitly-typed local variables must be initialized”

It’s mandatory to use an initial value; this is because the system infers the type of the variable based on the initial value assigned. Some of you may argue that instead of int and string we are using var and there is not much of a difference. I do agree, as implicitly typed variables were brought to support anonymous types (we will see anonymous types in a future blog) and they can very well be used to write terse code, another use of implicitly typed variable.One can really see the advantages of using var when one uses generics. Suppose you want to create a generic dictionary to hold two of your custom objects like User and his Address, a typical code to declare the dictionary would look something like this.

Dictionary<User, Address> userAddress = new Dictionary<User, Address>();

One can make out from the above code that there is a lot of repetition in the form of “Dictionary<User, Address>”. With implicitly typed variable we can shorten our code as shown below.

var userAddress = new Dictionary<User, Address>();

The User and Address classes are shown below. The properties are declared using Automatic Properties.

/// <summary>
/// User class stub.
/// </summary>
public class User
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public string Email {get; set;}
    public string Password {get; set;}
    public string PhNo {get; set;}
    public string Country {get; set;}
}

/// <summary>
/// Address class stub.
/// </summary>
public class Address
{
    public string HouseNo {get; set;}
    public string HouseName {get; set;}
    public string StreetName {get;set;}
    public string City {get;set;}
    public string Country {get;set;}
    public string ZipOrPinCode {get;set;}
}

The User and Address class objects can be initialized using the var keyword as shown below.

var user = new User();
var address = new Address();

One can use the var keyword to declare variables for any class. Few e.g. are shown below.

var dataset = new System.Data.DataSet();
var con = new System.Data.SqlClient.SqlConnection();
var lbl = new Label();
var txtBox = new TextBox();
var stringBuilder = new System.Text.StringBuilder();

Implicitly typed variables can be used with “for” and “foreach” loop, with “using” statement and for collection initialization. The following e.g. show each in action.

//Collection intialization using implicitly typed variable.
var colors = new[] { "Red", "Green", "Blue", "Yellow" };

//Implicitly typed variable used in a for loop.
for (var i = 0; i < colors.Length; i++)
{
      Console.WriteLine(colors[i]);
}

//Implicitly typed variable used in foreach loop.
foreach (var color in colors)
{
      Console.WriteLine(color);
}

//Implicitly typed variable used along with using statement.
using (var fileStream = new System.IO.FileStream("C:\test.txt", System.IO.FileMode.Open))
{/*Code goes here */}

As I said earlier, many of will say using “var” or implicitly typed variables do nothing more than saving a few lines of code but in realty implicitly typed variables were introduced in C# 3.0 to support Anonymous types. As the name suggests anonymous types don’t have any type. We will have a detailed look at Anonymous types in my next blog. Just to give a brief idea on anonymous types see the below LINQ code.

//Stupid code to fill the an array with User objects
var users = new [] {new User(), new User(), new User()};
/*LINQ query which creates an anonymous object with FirstName, LastName and Email as its properties. */
var indian = from u in users
             where u.Country.Equals("India")
             select new {FirstName = u.FirstName, LastName = u.LastName, Email = u.Email};

The above code makes use of LINQ query to filter out User’ whose country equals “India” and creates an anonymous object collection with FirstName, LastName and Email as their public property. The “where” extension method in LINQ filters the user’ with country as India and the “select” extension method creates the anonymous type with properties FirstName, LastName and Email. If one wants to make use of the anonymous collection type, indian, then he/she has to use the var keyword in the loop as shown below.

// foreach statement making use of the anonymous collection.
foreach (var ind in indian)
{
       Console.WriteLine(ind.FirstName + " " + ind.LastName);
       Console.WriteLine("Email: " + ind.Email);
}

Some people would obviously compare the var keyword with that of the one in javascript. Other than the similarity in spelling there is no other similarity. In javascript, once you declare a variable using the var keyword you can pump any type of data into it but that is not the case with C#. Once the system has inferred the type of the variable declared using “var” keyword one cannot reassign some other datatype to the variable.

var i = 6;
i = “trying to do something stupid”;//Not allowed

Whereas the same can be done in javascript.

<script language="javascript" type="text/javascript">
   var i = 10;
   document.write(i.toString());
   i = 'Reassigning something else.';
   document.write(i);
</script>

The variable “i” was initially assigned an integer value 10 and then a string was reassigned. This is very well allowed in javascript but not possible using the “var” keyword in C#. Once a variable’ type is inferred by C# using the initial value it cannot be changed. The reason is that behind the scene the variable is strongly typed using the initial value. This is why there is an insistence to provide initial value while using “var” keyword. By putting this restriction, one of the key features of C#, strongly typed language, is not done away with.

Some points to note

  • var keyword was introduced to support anonymous types and overuse of var in your code can make your code terse but hard to understand.
  • var can only be used on local variables i.e. methods declared inside a method.
  • var cannot be used to initialize a variable to null.
  • var can be used in “for” loop, “foreach” loop and in “using” statement as shown in e.gs above.
  • Class level variables cannot be decalred using the var keyword.

In the next blog we will have a look at Object Initializers and Collection Initializers, till then try to know more.

Sandeep

2 comments:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    dot net training center in chennai | Dot Net Training in velachery

    ReplyDelete
  2. You done excellent work with us. I am very happy to here and share with my good friends. Now it's time to avail vacuum sealer bags for more information.

    ReplyDelete

Please provide your valuable comments.