Jun 25, 2008

C# var - the difference between invariant type (JavaScript and other languages) and C#

The var keyword in C# (which is not even a keyword as you are permitted to create a class "var") is different from javascript.
The difference is that once assigned, a variable pefixed with a var "keyword" will have the type of what was assigned and will only allow you to assign object of the same type to this variable (or objects which inherit from that object).

Here is a brief example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace LINQ
{
  
class Program
   {
    
static void Main(string[] args)
     {
        Sample();
     }
    
static void Sample()
     {
        
style="color:Blue;">var a = new object();
        a =
new OperationCanceledException();
        
Console.WriteLine(a.GetType().Name);
     }
   }
}

Note, that we first assign new object to the variable a. After this assignment, "a" will only accept variables of type object (or any other type, which inherits from object). Then we assigned OperationCanceledExceptionObject (which inherits object type through Exception). If you try the opposite - to first assign
OperationCanceledException variable and then object you will end up with exception.


Conclusion: with var you are forcing the compiler to infer the type of the right side variable automatically. You will not need to declare what the type of variable should be. This saves you the following:

object a = new object();

What's nice is that Microsoft Visual Studio 2008 will be able to determine the type of a also and offer you intelisense.

No comments: