Home » none » CSharp VAR Misconceptions

CSharp VAR Misconceptions

G07L0003

I find it amazing that .NET 3.5 has been out for over a year and people still don’t understand the “var” keyword.

Just last week I got a comment on one of my videos asking why I used “var” so much.  Isn’t that only supposed to be used when you don’t know what the return type is going to be?

Clearly, this person does not understand what “var” does or how it should be used.

You see, the var keyword can ONLY be used when you know the return type.  It isn’t the same as a variant in VB6.

var str = "abe";

gets converted to

string str = "abe";

In fact if you write

var str;
str = "abc";

You will get the compiler error

“Implicitly typed local variable must be initialized.”

Why?  Because the compiler looks at the type of the variable or constant on the right hand side to determine what the variable type is so that it can strongly type the variable.

There isn’t any way of using “var” as a “figure this out at runtime” specified.  Everything happens at compile time based on what the compiler can determine about the variable type being used on the right-hand side.

In my day-to-day code, I don’t use “var” all that much.  It kind of looked cool when I started but old habits die hard and with intellisense it doesn’t really buy me that much in terms of saving keystrokes while I’m writing my code.  It kind of makes the code hard to read, too.

So while the understanding is wrong, the practice is right.  Only use var when you NEED it.

If you needed a variable that looked like a variant, what would you use?

An object.

If you clearly understand object oriented programming, you know this.  The Object class is the parent class of all other types in .NET.  Therefore you can assign any variable to to a variable declared as type Object.

Other places talking about CSharp VAR:

Var Wars – Abuse of the CSharp var – CSharp 3.0 introduced the var keyword for declaring variables without having to explicitly specify the type. This was done for using anonymous types returned from LINQ queries. Now, I am seeing many developers use it all over their code …

Local Type Inference (var keyword) (C#) – C# Language Features Tutorials.

Usage of the var Keyword in C# – Blaenk Denum – The question is, when should one use the var keyword? Take a look at this Stack Overflow question: What’s the point of the var keyword? In it, people note that using var can actually save you some time and in some cases make code a lot …

Like this Article? Subscribe to get every article sent to your email.

Related Post

  • What is .NET’s Object.GetHashCode() Used For?What is .NET’s Object.GetHashCode() Used For? Here is a great question from a visitor. “What is the exact use of GetHashCode of an object in .net? Does it have any relation with garbage collection?” Let's answer the second […]
  • Determine The Role of a User in ASP.NETDetermine The Role of a User in ASP.NET There are several controls that allow you to display content based on the role a user is in, including: - LoginView - LoginStatus And the web.config file allows us to control which […]
  • Readonly variables in CSharp? Really?!Readonly variables in CSharp? Really?! I'm sure most of you are familiar with the keyword "const," which allows you to declare a variable and give it a value and assures that no other code will change the value. const int v = […]
  • Type Safe Session VariablesType Safe Session Variables This may be obvious to everyone else on the Internet.  Heck, it's been obvious to me for several years.  But I can’t find anyone else writing about this and it makes so much […]
  • Self Executing Anonymous FunctionSelf Executing Anonymous Function Not because it is all that new, but because it took me a while to find it, here’s how to create a self executing anonymous function using CSharp, just like you can do in JavaScript. […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer. His commitment to quality through test driven development, vast knowledge of C#, HTML, CSS and JavaScript as well as his ability to mentor younger programmers and his passion for Agile/Scrum as defined by the Agile Manifesto and the Scrum Alliance will certainly be an asset to your organization.

  • Jaspio

    I don’t use var that much either. Except in foreach iterators:

    foreach (var item in collection) {}

    It saves a lot of trouble casting to the right type there.
    Good point on the right-side assignment though!

  • gunteman

    No, it doesn’t save you from casting, it saves you from explicitly declaring.

  • Mitch

    @gunteman

    I think we all know what he meant.

  • http://thelimberlambda.com/ Eric Smith

    The initial requirement for var was to make things like Linq possible. These days it’s just a nice way of applying the DRY principle – why repeat yourself when you don’t have to? On the other hand though, if it is not pretty clear what type we’re dealing with (other than when using anonymous types of course), then it probably makes sense to be explicit about the type.

  • gunteman

    @Mitch

    Yes, just making sure… :)

    CodeRush Express (free) features a “Make Explicit” function which can resolve “vars” when you feel like having the type explicitly declared.

  • http://hkdennis2k.homeip.net/ Dennis

    I use “var” a lot, except some foreach iterators to “xxxCollection” which “var” cannot works very well.

    In case I cannot use “var”, or it does not look very well; I should consider to break the method into smaller pieces and renaming stuffs.

    “var” really save a lot heartbeat from long type name (e.g. generic)
    “var” save some time when we extract a new interface from an object. (especially with a factory method)

    “var index = 1;”
    should be prevented, because “1” should be a constant.
    const int FOO=1; // I mean it
    var bar= FOO;

  • Mitch

    @Dennis

    var index = 1;

    should be avoided only WHEN index is a constant.