Coffeehouse Thread

72 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

How much do you use "var" in C#?

Back to Forum: Coffeehouse
  • User profile image
    Blue Ink

    While watching the video of Anders Hejlsberg, I happened to notice how he apparently uses "var" almost for everything, while I use it extremely sparingly, if at all.

    I realize it's mostly a matter of personal preference, but he being the father of C#, I wonder if this is what the language is really supposed to look like... what's your take on "var"?

  • User profile image
    Dr Herbie

    I only use var for the occasional anonymous type, or when I'm doing complex linq (like grouping) and find that I can't guess the output type.

    I prefer explicit types: this is C#, not PHP!

    Herbie

  • User profile image
    BitFlipper

    I use it all the time. It makes the code neater when you have a long list of different types of variables.

  • User profile image
    vesuvius

    You should use it all the time, it removes repetition.

    VeryLongClassName veryLongClassName = new VeryLongClassName() reads far much worse than

    var veryLongclassName = new VeryLongClassName();

    It really isn't about preference but about readability. The only time not to use var is when you are returning something like an IAsyncResult or a Dictionary, where it helps to be explicit about what the variable is.

    Why repeat the same thing thrice?

     

  • User profile image
    magicalclick

    I only use it for temporary local variables. Meaning I am going to use it right away and be done with it. But, most of time I prefer strong type. Var is less predictable, which I don't like.

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    BitFlipper

    How so? It is just as strongly typed as anything else.

  • User profile image
    magicalclick

    It is not strongly typed at compile time, unless I am wrong. The compiler can validate the type before runtime?

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    vesuvius

    It is strongly typed at assignment time, that is what type inference is, validation has nothing to do with it.

    You can only use it within the local scope of a method anyway. If you think about it, the original question is asking if the Chief Architect of the C# Language and .NET Framework is wrong, and does not know what he is doing?

    Anders is right, and you should use var wherever it improves readability, and omits triplicate duplication in declaring variables.

  • User profile image
    Sven Groot

    It is strongly typed. If you mouse over the variable in the IDE it'll even tell you what type it is, and everything is checked by the compiler the same as if you had explicitly named the type. The type is statically determined by the compiler based on the expression that initializes the variable, and cannot change afterwards.

    Don't confuse "var" with "dynamic".

     

  • User profile image
    ManipUni

    What is the performance penalty of var?

    Are these two statements identical in the byte code:
    StringBuilder something = new StringBuilder();
    var something = new StringBuilder();

    Also, if they're identical then why use a var at all? Readability is only a mild argument. If you cared about readability you'd be using Visual Basic .Net to begin with.

    Last question is - look at this code and tell me what type it would be assigned:

    var foo = null;
    try
    {
    Bar.Create(foo, Bar.SuperBar);
    if(foo == null)
    throw new Exception("I dun failed!");
    }
    catch(Exception ex)
    {
       // I only made this exception handling block to create a realistic scenario involving null assignment
    }
    Response.Write(foo.DoSomething(Bar.MagicalBar));
    Response.End(); 
    

  • User profile image
    joechung

    var foo = null; will fail, because it is not specific enough for the type to be inferred.

    var something = new StringBuilder(); is equivalent to StringBuilder something = new StringBuilder();

    You would type that, because it's fewer keystrokes and less redundant.

    I use var all the time in my own code.  I rarely use it in work code, because, as demonstrated in this thread, most don't understand how var works and make erroneous conclusions about its usage.

  • User profile image
    vesuvius

    @ManipUni: At the moment I am writing in both C# and Visual Basic (not out of choice mind). In general once you have a complex application, long namespaces and classnames are inescapable, and I like to read a line of code without having to use my scroll bar, so var makes things very readable where the verbosity of Visual Basic can be counter to your assertion above.

    Your code also would not compile as the first line would raise an error saying that you cannot assign a null value to an implicitly signed variable.

     

  • User profile image
    Sven Groot

    The main place where I'll use var is in a scenario like this:

    foreach( KeyValuePair<string, int> item in dictionary )
    {
    }
    
    // Becomes a lot easier with
    foreach( var item in dictionary )
    {
    }

    I rarely use it for regular locals.

    And yeah, the type must be possible to inferred from the initialization of the variable, so Manip's sample doesn't compile.

  • User profile image
    magicalclick

    I see. I thought it is dynamic. But, since it cannot change typy after first call. I will do it. Yeah, it should be cleaner because now I can see all the var similar to Dim.

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    magicalclick

    @joechung:

    Hehe, that's me.

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    ManipUni

    So var is unusable when you are using any kind of exception handling around initialisation? That seems like a massive drawback to its usefulness.

    You're stuck between a rock and hard place, you need to define variables outside of the exception handled blocks (since the compiler cannot predict the route the execution will take within that context) but to a var you must initialise them to a type in order to use them.

    How about this example, how would you refactor this into a var version of the same?

    StreamReader sr = null;
    string content;
    try
    {
        sr = new StreamReader(@"C:\Temp\example.txt");
        content = sr.ReadToEnd();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Source: " + ex.Source + " Message: " + ex.Message);
        return; 
    }
    finally
    {
        if(sr != null)
            sr.Close();
    }
    Console.Write(content);
    Console.ReadKey(); 

  • User profile image
    Sven Groot

    You cannot refactor that to use var. Var can only infer the type from the variable's initialization expression, and in this case it has none.

    Var was primarily designed for use with LINQ, where the result of LINQ expression can be very complex to express explicitly, or even include anonymous types (in which case it can't be expressed explicitly).

    I guess in theory you could create a compiler under which your example works (infer the type using the first assignment if it has no initialization), but that would strain the boundaries of readability and run into issue if determining what's the first assignment is ambiguous.

  • User profile image
    Michael Butler

    I use var a lot in foreach statements but have also started to use it more often when my class names are large and it becomes easier to write var repository = new SqlCustomerBookingRepository();

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.