Search Unity

C#: Microsoft suggests using var instead of a type?

Discussion in 'Scripting' started by GarthSmith, Mar 6, 2014.

  1. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    I'm reading the C# Coding Conventions used on MSDN and I came across this sentence under the section "Implicitly Typed Local Variables".
    They go on to show some examples.
    Code (csharp):
    1.  
    2. // When the type of a variable is clear from the context, use var
    3. // in the declaration.
    4. var var1 = "This is clearly a string.";
    5. var var2 = 27;
    6. var var3 = Convert.ToInt32(Console.ReadLine());
    Code (csharp):
    1.  
    2. var syllable = "ha";
    3. var laugh = "";
    4. for (var i = 0; i < 10; i++)
    5. {
    6.     laugh += syllable;
    7.     Console.WriteLine(laugh);
    8. }
    9. // ...
    10. foreach (var ch in laugh)
    11. {
    12.     if (ch == 'h')
    13.         Console.Write("H");
    14.     else
    15.         Console.Write(ch);
    16. }
    17. Console.WriteLine();
    18.  
    This seems insane to me!

    What possible reason could there be for Microsoft recommend this?
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    That's what I do. It's stupid, IMO, to do stuff like "Dictionary<String, Material> someVar = new Dictionary<String, Material>()" when you can just do "var someVar = new Dictionary<String, Material>". The first way is excessively verbose and adds nothing to the code except useless repetition, without enhancing comprehension.

    I'm not so sure that those examples actually demonstrate this, however. The "foreach (var ch in laugh)" part is sufficiently divorced from the declaration of "laugh" that it's not completely clear from the context what type "ch" actually is. You have to go back and scan the previous code to figure it out. And it's really not hard to type "char" instead of "var".

    --Eric
     
    MikeM1970 likes this.
  3. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Okay, after my shock subsided a bit, I went and checked it out a bit more. My confusion comes directly from knowing that var in JavaScript is NOT typed. (EDIT: Eric mentions that in UnityScript it IS typed. Confused yet? =p ) In C#, var is still typed. When MSDN says "Implicitly Typed Local Variables" it means something apparently. ='p
    Code (csharp):
    1.  
    2. // completely acceptable in JavaScript.
    3. // EDIT: But apparently not in UnityScript?
    4. var x = 4;
    5. x = "John Doe";
    6.  
    Code (csharp):
    1.  
    2. // Eventually generates a compiler error in C#
    3. var x = 4;
    4. // x.GetType() returns Int32.
    5. // Next line causes a compiler error.
    6. x = "John Doe"; // ERROR!!!
    7.  
    I've been typing every single variable since I picked up C#.
     
    Last edited: Mar 7, 2014
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Also in Unity Javascript, where it works basically the same way as C#. Implicit typing is not the same thing as dynamic typing.

    --Eric
     
  5. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Ah one of those infamous UnityScript is not JavaScript things! Good to know if I ever write some .js code.
     
  6. Diviner

    Diviner

    Joined:
    May 8, 2010
    Posts:
    677
    Take everything you read in MSDN with a grain of salt. Their documentation is far from stellar.
     
    Fenikkel likes this.
  7. spraycanmansam

    spraycanmansam

    Joined:
    Nov 22, 2012
    Posts:
    254
    This. I code as explicitly as possible at all times, with the only exception being Eric's example. My basic rule of thumb is if I need to look anywhere else other than the same line, or if the declaration isn't clear enough (that I have to hover over the var keyword to check for eg) than I should have explicitly typed it.
    I disagree with the MSDN a lot of times :p
     
  8. Paragon99

    Paragon99

    Joined:
    Nov 23, 2013
    Posts:
    54
    Actually I think the reason they promote that syntax is to help extensibility and scalability.

    Microsoft talks about software from an ongoing continuous development perspective. They want to help make code as future proof as possible.

    If you use an explicit variable type then In the future you have to change all that code again in the future if you change the type you are using, if you use var, then changing the type in the future gets propagated implicitly. This is particularly true for looping variables. The least amount of helpfulness is something like

    Foo f=new Foo(); // Changing Foo to bar requires two changes
    var f=new Foo(); //Changing Foo to bar requires a single change.

    foreach (foo f in collection) //Chaning collection to a collection of bars requires a change
    {
    dosomething(f);
    }

    foreach(var f in collection) //Changing collection to a collection of bars requires zero changes.
    {
    doSomething(f);
    }
     
  9. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    i consider this a strong pitfall. when you are forced to check every affected statement manually because the compiler complains you have way more controll and possibilities to ensure it works than when it happens silently.
    in my opinion changing the type of a variable is not refactoring its more of a rewrite of a portion of code. and it should happen (and does for me) rarely. and when it does i don't want the compiler to do the rest but i want to check if it works as i imagine or not.

    @Garth: i don't believe blindly in microsofts suggestions any more since they recommended hungarian notation for C++ (MFC) and now they recommend you should NOT use it. so their opinion changes with "fashion" and thus is just that, an opinion. not the philosopher's stone.
     
  10. jackmott

    jackmott

    Joined:
    Jan 5, 2014
    Posts:
    167
    var is a complete waste of time imho.
    I can at least see the appeal in cases of complex type names like the Dictionary<type,type2> example, but a good editor auto-completes that anyway.

    I'd rather pull the feature out entirely, code will build a couple ms faster, everyone will be forced to be consistent.
     
  11. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    This is true, however if the type you're changing is in a separate assembly you'll still have to recompile both. By "Implicitly Typing", it means that the compiler determines the correct type at compile time.


    If you think it's a waste, don't use it. I think it's very useful and can make your code much cleaner (such as in Eric's example above), but shouldn't be used in all cases. For example:

    Code (csharp):
    1.  
    2.     //It's obvious that ToString is going to return a string
    3.     var myVar1 = someObject.ToString();
    4.  
    5.     //Here it's not clear what type myVar2 will be
    6.     var myVar2 = SomeOtherFunction();
    7.  
    8.     //Here both the variable and function give a pretty good idea of what we're getting
    9.     var personInstance = GetPerson();
    10.  
    11.  
    Another thing to keep in mind is that "var" only works when you're combining your declaration and assignment. You can't do this:

    Code (csharp):
    1.  
    2.      var foo;
    3.  
    4.      foo = string.Empty;
    5.  
    6.  
    That won't work in C# because at the line where it declares "foo" it needs to know what the type is to compile it and it won't infer it from the context further down. Also, you can't use var when declaring fields within classes / structs.
     
  12. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    I actually find their documentation to be quite good. I'd take MSDN over Oracle's Java documentation any day. The issue is that they break their own conventions constantly, which sort of doesn't make them conventions anymore...
     
  13. Flipbookee

    Flipbookee

    Joined:
    Jun 2, 2012
    Posts:
    2,793
    I think var in C# is great and I'm using it everywhere recently. It feels like the compiler is taking care of half of my job. Changing field types is so much easier now as it only requires that to be done in one single place in best case, or in a few places more eventually but then the compiler finds them all at once for me. It's a great timesaver when working with complex algorithms!

    Still, I see this as a personal preference of the programmer, although I'd prefer to work on someone else's code with var's. In coding theory these two styles are called WET and DRY principle (see http://en.m.wikipedia.org/wiki/Don't_repeat_yourself).

    In terms of what compiles faster var's will always win! Parsing a simple var keyword is cheaper than explicit types, as it doesn't involve symbol resolution and there's no need to verify is the conversion of the assigned value valid or not.
     
  14. Kasse

    Kasse

    Joined:
    Dec 20, 2013
    Posts:
    18
    Well in my opinion it's readability vs. usability. However i think it's crap. I like to just see the blue text and know what's going on. I guess if you get used to it var is just fine and might have some benefits. I still kind of hate it. Maybe that's because it always remembers me of languages like js which i just hate. I'm really happy with my C# typesafety and am really grateful i don't have to care about the mentioned cases of simple bullshit you can do with js.
     
  15. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    I stay away from var. I don't like implicit stuff. Like a woman that assume you understand what she's not telling you. :p
     
    MoonbladeStudios likes this.