C# and var keyword

C# 3.0 introduced us new language feature: type inference using keyword var. Some guys think that var in C# is same thing as var in PHP. That's wrong - var keyword in C# is totally different thing and it doesn't mean that C# has now support for type changing class attributes. Let's prove it.


NB! This blog is moved to gunnarpeipman.com

Click here to go to article


  • Thats nice stuff to read. Thankyou.

    Bharath Reddy VasiReddy

  • How does the keyword var make code more readable? If anything it makes code non deterministic. This is nice for the dynamic natures of Lambda and LINQ expressions, but it does NOT make code more clear. If another programmer comes along 2 years later are they going to really understand what type is assigned to a var variable without first digging deep into what is returned? There are tons of blogs out there highlighting why you should NOT use var outside of dynamic languages and structures. In most scenarios specifying the type is preferred over var.

  • By the way, null can be assigned to var as long as type inference can be determined by the expression such as:
    vat x = null as object;

    However you might as well say:
    object x = null;

    It's shorter and clearer anyways.

Comments have been disabled for this content.