Click here to Skip to main content
15,936,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what is the function of var keyword

What Uma tried to explain is called type inference, introduced in C# v.3. See:[^],[^],[^].

I found pretty nice short explanation here:[^].

Pay attention of type inferred from a constructor, this is a most important case:

var myInstance = new MyClass.Create(/*...*/);

//strictly equivalent to 
MyClass. myInstance = new MyClass.Create(/*...*/);
// (only without a need to write MyClass twice...)

Type can be inferred from container in foreach, type of parameters inferred from the type of delegate:

myTextBox.KeyPress = (sender, eventArgs) => {
    // eventArgs can be used as KeyPressEventArgs,
    // inferred form the declaration of the event TextBox.KeyPress

This is another important case of inference, practically the most important one.

Share this answer
Uday P.Singh 19-Oct-11 3:25am    
my 5, please see my solution as well!
Sergey Alexandrovich Kryukov 19-Oct-11 3:26am    
Thank you, Uday, I will.
var is used for implicitly typed local variable, which is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

For more info refer these:[^][^]

var is basically used in LINQ where we don't know what type is returned from the query result.

hope it helps :)
Share this answer
Sergey Alexandrovich Kryukov 19-Oct-11 3:28am    
Yes, good point about strong typing, could help to prevent a common misconception, also -- different links, so we did complementary -- team work. I voted 5.
Uday P.Singh 19-Oct-11 3:36am    
Thanks SA :)
The var keyword can represent any type that can be determined at compile-time.
For Example
public int ReturnValue()
    var a = 5;
    int b = 5;

    return a + b;
Share this answer
Mehdi Gholam 19-Oct-11 3:10am    
my 5!
Sergey Alexandrovich Kryukov 19-Oct-11 3:22am    
I voted 4. This is basically correct, but... not really clear and not complete. MSDN references explain it all -- please see my answer.
Like Uma said var is a shortcut while writing your code but is type safe when compiled (ie at compile time the object type is known).

I presume the var keyword was added by Microsoft so you can easily port more JavaScript code to c#.
Share this answer
Sergey Alexandrovich Kryukov 19-Oct-11 3:24am    
I doubt port from JavaScript was one of the reasons. Also, this topic has a lot more, and your and Uma's explanation do not really explain things; not even terminology is mentioned... Please see my solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900