C# 3.0 Tutorials: Implicitly typed local variables

This is the third article of C# 3.0 tutorial series. We will take a look the first feature called “Implicitly typed local variables declaration” in this article.

What is Implicitly typed local variable?

Implicitly typed local variable is a variable that can be declared without specifying the .NET type explicity. The type of that variable will be inferred by the complier from the expression on the right side of initialization statement.

Let me show you the simplest sample of “Implicitly typed local variable”. Let’s think about the way that we declare the variable in C#. Normally, we used to declare the variable with a specific type, right? For example: int i = 1; In implicitly typed variable declaration, you don’t need to write “int”. You don’t need to set that the type of variable “i” is integer type. Instead, you can use the brand new C# 3.0 keyword “var” in that place. So, the code will be like that. “var i = 1;” As the value that assigned to “i” variable is 1, the type of “i” variable will be Integer automatically.

“var” is not like object or varient type that has expensive cost. That type of that variable will be changed to the actual .NET type based on what value you have assigned to that variable. As I mentioned in example above, if you assign 1 to i, the type of i will be integer data type.
Let’s open Visual Studio 2008 and create one C# console application. then, open the Program.cs and type the following code in Main().


var i = 1;

then, type “i” “.” (dot) and check-out the intellisense. You will see it as the screenshot below. Then, try to declare the int variable (let’s say “j”) in normal way and check what you have in intellisense for that new integer variable “j”. You will get exactly the same thing like what you get for variable “i”, the implicitly type local variable. That means variable “i” become integer type based on the value that we initialize.

Implicitly typed local variable

Fig: 1.0: the variable "i" as integer data type.

Okay. Let’s change the initialized value of variable “i” from 1 to “This is a string”.


var i = "This is a string";

Then, type “i” “.” (dot) and check-out the intellisense again. What you saw in intellisense is changed now. (You can compare both screenshots.) The type of variable “i” has been changed since we have changed the value “1″ to “This is a string” in declaration. So, you can think of “var” as a place holder where the compiler will replace the real data type based on what you initialize the variable.

Implicitly typed local variable

Fig: 1.1: the variable "i" as string data type.

This is the basic things about implicitly typed local variable. You can declare any kinda data type as I mentioned in the example below.

var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int,Order>();

Restrictions

Before you start using the implicitly type variables, you should know that there are a few restrictions of using that type of variables. (Ref: C# 3.0 Specification)

  1. The declarator must include an initializer.Unlike normal declarations, you can’t declare the implicitly type variable without initializing. For example: The following code won’t be complied.
    var test; // ERROR: Implicitly-type local variable must be initialized.
    
  2. The initializer must be an expression. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer.You can’t initialize it with an array. For example ~
    var test =  { 1, 2, 3 }; //Error    1    Cannot initialize an implicitly-typed local variable with an array initializer
    //Error    2    Can only use array initializer expressions to assign to array types. Try using a new expression instead.var test1 = new[] { 1, 2, 3 }; //This is correct!!
    
  3. The compile-time type of the initializer expression cannot be the null type.
    var test =  null; //ERROR
    
  4. If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type.The implicitly-type local variable cann’t be initialized with different types more than one time. You can’t assign the string to varaible “test” after initializing with integer value “1″.
    var test = 1;
    test = "This is a string"; // ERROR
    

FAQs

Whenever I discussed with a few developers about that type of variables, they used to ask me the following questions.

Q #1: Why do we need to use “var” when we can declare the variable with real data type?

A #1: Yes. You don’t need to use “var” if you know what type you want to use. This is not what it is designed for. If you know the type then use the type.

Q #2: Let’s say I wrote like that “var myvar = 1;”. then, C# compiler will assume my variable “myvar” is int, right? Actually, I declared it as long.. How can I make the compiler to know my variable “myvar” is long data type. What about “int vs uint”, “long vs ulong” and “double vs float vs decimal”??

A #2. Initially, I also had that doubt in my head. ( Thanks to Codeproject members who cleared that doubt from my mind.) Actually, this is the variation of previous question. Even though you can declare as the code below, you should not use it because as I told you earlier, if you know the type then use that type.

var ui = 1U; // uint
var l = 42L; // long
var big = 1234567890UL; // ulong
var pi = 3.1416; // double
var size = 12.5F; // float
var price = 27.99M; // decimal

Conclusion

What I would love to say for conclusion is that ~

  • The implicitly typed local variables is not an object or variant.
  • “var” is just like a placeholder where the compiler will replace the actual datatype based on what you initialize with.
  • You shouldn’t use implicitly-typed local variable if you know the type.
  • “Implicitly-typed local variables” are the best things to use when you are dealing with anonymous type or LINQ.

Thanks.

C# 3.0 Tutorials: Object and Collection Initializers

Howdy everybody! This is the second part of my C# 3.0 tutorial series in my blog. Today, we are gonna talk about object and collection initializers, one of the features of C# 3.0.

This feature allows you to initialize the entity object or collection in very easy way that we’ve never done before. When I was working for .NET 1.1 or 2.0 projects, I used to create at least three constructors in each and every entity classes just for making rich-constructors that helps the developers to initialize easily.

For example ~

public class Cat {
#region private variable declaration
private int _catID;
private string _name;
#endregion

#region constructors
public Cat() {
}
public Cat(string name) {
_name = name;
}
public Cat(int id, string name) {
_catID = id;
_name = name;
}
#endregion

#region properties
public int CatID{
get{
return _catID;
}
set{
_catID = value;
}
}

public string Name{
get{
return _name;
}
set{
_name = value;
}
}
#endregion

}

The reason why I created those constructors is that it make the developer’s life easier to initialize the object as below.

Cat cat = new Cat(1, "Pepsi Ko");
Cat anotherCat = new Cat("Ordico");

but just imagine that what if we have 100 entity classes with 20 or more properties. Creating three constructors for those classes would be time-consuming process, isn’t it? if you are a project manager of the team, you can simply ask your developers to add those constructors in each entity class. but sometime, you don’t have that level of control all the time. then, you will end-up writing the code below.

Cat cat = new Cat();
cat.CatID = 1;
cat.Name = "Pepsi Ko";

Cat anotherCat = new Cat();
anotherCat.Name = "Ordico";

With C# 3.0, you don’t need to write those constructors and you don’t need to ask anyone to create the constructors for you. You can simply initialize the object as below ~

Cat cat = new Cat { CatID = 1, Name = "Pepsi Ko" };
Cat anotherCat = new Cat { Name = "Ordico" };

It’s pretty cool, isn’t it? It saves some of your typing time and copy-n-paste works. :) If you are using VS 2008, you will get cool intellisense that can tell you what properties you have initialized.

VS Intellisense for Object Initializer

VS Intellisense for Object Initializer

If your entity class has the object of another class as a field then you can also initialize the contained class as below.

Let’s say you have the class like below ~

public class Cat {
public int CatID { get; set; }
public string Name { get; set; }
public List<Cat> Children { get; set; }
}

then, you can initialize like below ~

Cat mamamCat = new Cat { CatID = 1, Name = "Pepsi Ko",
Children = new List<Cat>{
new Cat{ CatID =11, Name = "Pussy Lay" },
new Cat{ CatID =12, Name = "Kitty" },
new Cat{ CatID =13, Name = "Soemasoe" }
}
};

All right. This is all about object and collection initializer. The advantage of using this feature is that it save some of your time for creating a lot of constructors or initializing the individual property. That’s all. If you have any comment or suggestion, please let me know. Thank you!