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>();


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


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


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.


18 Replies to “C# 3.0 Tutorials: Implicitly typed local variables”

  1. “That type of that variable will be changed the actual type based on what you have assigned to that variable”
    Sorry, but I don’t understand the meaning.
    By the way, nice blog.

  2. Sorry, but I don’t understand the meaning.

    thanks for your comment. What I meant by that is that the type of implicitly-typed local variable will be changed based on what you initialize to that variable. For example: var myvar = 1; myvar is not an object or variable. myvar is integer data type since you have initialized the value “1” to that variable..

    hope you understand about that. feel free to let me know if you are still not clear about that.

  3. Now i’m following this tutorial series. :) Thanks for the great tutorials!! I have worked on C#, like one and a half year ago. Just take over other ppl’s project without digging all these basics grounds of C#. What a lazy programmer I hv been! These are tutorials which indeed helpful to me. Waiting for the later episodes…

  4. lets say i have store the values from linq store procedure into var
    var selectedProduct= storeProcedure of linq
    now i want to see if selectedProduct is null or empty
    i tried with
    but none worked
    so any suggestion that tell me that that var is empty or null or do not have any value
    thanks in advance

  5. Can you show me your LINQ code? Normally, you can check the count of var..

    Option #1.


    Option #2.

    bool isFound = false;

    var selPdt = LINQ;

    foreach(var i in selPdt){
    isFound = true;


  6. Here’s a question, unfortunately I don’t have VS2008 at hand to test it with.

    Now this is not great code but I just thought about

    Lets say, for the sake of hypothesising

    I have an interface called IMyInterface, I have an object called MyObject that implement IMyInterface.

    I have a function that has a return type IMyInterface, but actually returns an instantiated MyObject.

    I initialize my var with the return of this function.

    for brevity and in pseudo I do this.

    var myVar = MyFunction();

    does myVar become of type IMyInterface or of type MyObject when I’m dealing with it?

    I’m pretty sure visual studio will treat it as IMyInterface, because it’ll look up the return type of the function called in order to provide intellisense. But as to the compiler? hmm… I’ll have to test that. My Expectation would be IMyInterface, and if it wasn’t it’d be bad not to treats as IMyInterface, but it certainly provides food for thought.

  7. “You shouldn’t use implicitly-typed local variable if you know the type.”

    When would you not know the type?

  8. How do I initialize my “var” variable if I am going to use it outside the try statement like this:

    XDocument xdoc = XDocument.Load(@”C:\VisualStudio\myxmlfile.xml”);
    var res = ; //GIVES ERROR HERE
    res = from userNumber in xdoc.Descendants(“basicModule”) select userNumber.Element(“userNumber”).Value;
    catch (Exception)


    If I declare it inside the try-catch the initialization would be okay, but the it would not been known outside the try statement

    Best Regards

  9. Hi Pigbear,

    What will be the type of this “from userNumber in xdoc.Descendants(“basicModule”) select userNumber.Element(“userNumber”).Value”?

    If it’s string then you need to initialize that variable.

    var res = strine.Empty;

    Hope it helps

  10. Hi again,

    Im am trying to use linq to select data from an xml document.
    The document looks like:


    The userNumber is declared in the line:
    res = from userNumber in xdoc.Descendants(“basicModule”) select userNumber.Element(“userNumber”).Value;

    Actually I am not quite sure what type is returned from the xml document, but it does not help setting the var to a string

  11. .. still wrong I can see. The serverside code does not treat the xml I insert as regular text. So I replace the greater than/lower than with a –



  12. I m having a implicit type variable and i m using in lamda expression like
    var q = db.Talents.Where(x => (x.Paid == true || x.MembershipType == “AdminTalent”) && x.Archived == false)

    and if supposed var q showning “Enumerations having no results” then i want to give an error message
    my code is
    if (q == null)
    return jsonError(“no search found”)

    how we compare q(imlicit type local variable)

Leave a Reply