InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

C# Debate: When Should You Use var?

Posted by Jonathan Allen on May 28, 2008

Sections
Development,
Architecture & Design
Topics
Programming ,
.NET ,
Syntax
Tags
C#

C# 3 added the keyword "var". This allows for local type inference when the compiler can unequivocally determine what type the variable should be. There is, however, some debate as to when it should be used.

Ilya Ryzhenkov from the IDE tool company JetBrains outlines some benefits for using var,

  1. It induces better naming for local variables.
  2. It induces better API.
  3. It induces variable initialization.
  4. It removes code noise
  5. It doesn't require the using directive.

Dare Obasanjo of RSS Bandit does not agree. He wrote a response to Ryzhenkov's position after seeing what he thought of as detrimental changes to his open source project. He counters with,

It's interesting how not only are almost all of these "benefits" mainly stylistic but how they contradict each other. For example, the claim that it leads to "better naming for local variables" really means it compels developers to use LONGER HUNGARIAN STYLE VARIABLE NAMES. Funny enough, these long variable names add more noise to the code overall since they show up everywhere the variable is used compared to a single type name showing up when the variable is declared. The argument that it leads to "better API" is another variation of this theme since it argues that if you are compelled to use LONGER MORE DESCRIPTIVE PROPERTY NAMES (e.g. XmlNode.XmlNodeName instead of XmlNode.Name) then this is an improvement. Someone should inform the ReSharper folks that encoding type information in variable names sucks, that's why we're using a strongly typed programming language like C# in the first place.

One more thing, the claim that it encourages variable initialization is weird given that the C# compiler already enforces that. More importantly, the common scenario of initializing a variable to null before it is used isn't supported by the var keyword.

Dare backs up his claim with this line from the official C# Language Reference,

Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.

The complaint that var reduces readability is not shared by everyone. Arnon Rotem-Gal-Oz writes,

As for the code readability claim, I prefer to focus on stronger methods like keeping methods short, meaningful method and variable names and supporting tests (which can actually help you understand how the code behaves...). Not to mention that, if you really really need that, resharper will tell you the type if you put the mouse over the var keyword ;)

Chris Sutton seems to go further and implies that the type really doesn't matter.

Then the suggestion came up that you should only use var when you don’t know the type. Here is where I differ in opinion and usage. Look at the following snippet

var procs = from p in ServiceController.GetServices()
where p.Status == ServiceControllerStatus.Running
select p;
procs.ToList().ForEach(p=> Console.WriteLine(p.ServiceName));

procs is certainly IEnumerable but it doesn’t matter to me. I primarily care that procs is a list and that the individual items in the list have a Property called ServiceName. The underlying type is important to the compiler, but the people that have to read code aren’t compilers right?

I would say use var wherever you can use it by Sadek Drobi Posted
Re: I would say use var wherever you can use it by Jonathan Allen Posted
Re: I would say use var wherever you can use it by Sadek Drobi Posted
You use var when no one cares about the type. by Francois Ward Posted
When to use type inference by Shirvan Noormohammadifar Posted
Re: When to use type inference by Jeff Harris Posted
Re: When to use type inference by Ricardo Serradas Posted
  1. Back to top

    I would say use var wherever you can use it

    by Sadek Drobi

    var has a lot of benefits. It forces initializing to not null value, and it introduces flexibility inside the method scope as Chris illustrated in his example.

  2. Back to top

    You use var when no one cares about the type.

    by Francois Ward

    Often, the initialization is the only part that matters in a variable.



    - In LINQ queries


    - IN FOREACH LOOPS:foreach( var blah in someCollection), that one is big
    -Dictionnaries. The difference between a dictionnary that cares about case or doesn't depends on the comparer. People who look just at the type will miss that. Using var in that case force people to look at the initialization.
    -When using datasets/dataadapter, especially typed ones... the declaration gets rediculous and is just noise.

    There's more. You shouldn't use var everywhere, that reduces the information the code gives to a reader just by looking at it (without mouse overs). But the above scenarios clearly benifit from it. When you don't know the type and only the initialization matters (like foreach and linq), or when declaration just adds visual noise.


    Don't go using var blah = 12; that just takes away from the intention. Is that an int? A float? I know its an int, but I don't know if it was your intention...

  3. Back to top

    Re: I would say use var wherever you can use it

    by Jonathan Allen

    I don't know about that. I suspect most people would decide whether or not they are initializing to null first, then use var accordingly.

  4. Back to top

    Re: I would say use var wherever you can use it

    by Sadek Drobi

    Usually I don't like initializing to null, but sometimes I find myself forced to because of some language limitations. So I can agree with you.

  5. Back to top

    When to use type inference

    by Shirvan Noormohammadifar

    OK, there is always tradeoffs, Everywhere we want to use something in code we must have reasons for it, there aren't necessary reasons to push me for using type inference everywhere in my code, and here are drawbacks:


    yes of course, var is type safe but what is our gain in using it everywhere?




    compiler acts like this: when sees the var keyword it tries to find the type of variable based on the value assigned to it, this means that we can't assign a value that compiler can't determine it's type, and this results to:


    We can't use var when initializing a variable to null, cause compiler can't determine it's type.


    OK lets see another case, suppose we have the following line of code:


    var amount = 13;




    Now what is amount? int16, int32 or int64?


    or another example:


    var tax = taxCalculator.GetTax(amount);




    Now what is the type of tax???




    These are really confusing and it's not a good practice to use type inference in these situations.


    Or something like this:


    var firstName = "shirvan";




    What is our gain using var instead of string??? i think nothing.




    In DRY case I'm agree that repeating is unnecessary in variable declaration and in my opinion the right side type declaration is unnecessary and redundant, but to get rid of this redundancy c# compiler should take the responsibility and enables this feature(maybe in future releases) instead of using var and sacrificing readability.




    The var keyword is very cool feature in c# 3.0, I'm also a big fan of Intelligent laziness and less typing but i think it's not applicable here and we shouldn't use type inference everywhere in our code, the right place to use it is when dealing with anonymous types or a collection of anonymous types.




    Shirvan Noormohamadifar

  6. Back to top

    Re: When to use type inference

    by Jeff Harris

    Excluding arguments about the variable names, what about :

    NotificationClient client = new NotificationClient();
    NotificationRequest noteReq = new NotificationRequest();
    NotificationResponse noteResp = new NotificationResponse();

    1. That's redundant as heck and adds noise.
    2. It's not as visually aligned and tidy looking as this is:

    var client = new NotificationClient();
    var noteReq = new NotificationRequest();
    var noteResp = new NotificationResponse();

  7. Back to top

    Re: When to use type inference

    by Ricardo Serradas

    That's the answer! Here I agree completely.

    I think we should use var moderately. It's like alcohol here in Brazil: "Aprecie com moderação" ("Enjoy it moderately").

    In cases of variable initialization, it's great. Assigning a value which has an explicit type (like int or string) is good either.

    But use it in a variable which receives a response from a method is not good at all, like:

    var x = DoSomethingAndReturnSomethingElse("SomeValue");

    Well... Like almost everything: enjoy it moderately!

    Ricardo Serradas
    Visual Studio ALM in a nutshell - blog.ricardoserradas.net

Educational Content

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.

Beauty Is in the Eye of the Beholder

Alex Papadimoulis discusses ugly code, where it comes from, how to avoid it, and how to get rid of it.

Architecting Visa for Massive Scale and Continuous Innovation

John Davies examines Visa’s architecture and shows how enterprises have architected complex integrations incorporating Hadoop, memcached, Ruby on Rails, and others to deliver innovative solutions.

Max Protect: Scalability and Caching at ESPN.com

Sean Comerford unveils ESPN.com’s architecture, what components are used and why, and the current changes the website goes through.

The Seven Deadly Sins of Enterprise Agile Adoption

Are there repeated patterns of failure on Enterprise Agile Enablement efforts? Sanjiv and Arlen discuss Seven Deadly Sins to avoid when adopting Agile in an enterprise.

Questions for an Enterprise Architect

Erik Dörnenburg answers: What is Enterprise and Evolutionary Architecture?, discussing 4 issues: Turning strategy into execution, Ensuring conformance, Where do the architects sit? Buying or building?

Wrap Your SQL Head Around Riak MapReduce

Sean Cribbs explains what Map-Reduce and Riak are, why and how to use Map-Reduce with Riak, and how to convert SQL queries into their Map-Reduce equivalents.