Simple question: Should I be bothered by...



  •  ...this C# code:

     

    var showComment = false;

     

    It annoys me. Especially as it's code that I have produced that gets changed.

    Please can someone give me a reason why this is good practise? I don't think anyone can but if you can that would be helpful as I shall bring this (and other) cases up in my appraisal.

     

    My thoughts are 'var'  should only be used where neccesary OR when Class-names are really long and it aids readabilit eg.

    ReallyLongClassName reallyLongClassName = new ReallyLongClassName();

    would become:

     var reallyLongClassName = new ReallyLongClassName()

    ...and even then, it's pushing it.

     



  •  I'm not sure what the var keyword is doing in C#, but then again, I think the pattern:

    ClassName instanceName = new ClassName()

    is equally fucked.

     

    So, no, it doesn't look too good to me (and I'm a javascript afficionado), but then again, the time spent on these posts might have been better spent on useful code, so let's not get lost in useless details.



  • On the same line you can clearly see what the type is and when you see the showComment variable somewhere else you can just hover over it and also see that it's a boolean. I have no problem with this.



    If you want to be absolutely sure what the type is then you can use the following:

    global::System.Boolean showComment = false;

    Because not everyone knows that bool is actually Boolean, and that it's in the System namespace, and you could have a subnamespace System so you will need to use the global alias.



  • "the time spent on these posts might have been better spent on useful code, so let's not get lost in useless details."

     

    I thought the point of this forum/site was to debate, amongst other things, good/bad coding-practise?

     



  • @miner49er said:

    I thought the point of this forum/site was to debate, amongst other things, good/bad coding-practise?



    Indeed.

    Type inferernce has it's place, but don't use it just to make your code look Sexy/LinQy. If you mean a boolean, use a boolean. It makes you're code easier to read, and with more complicated datatypes also means that you get intellisense made available to you...

    Martin.

     

     



  • @muppetman said:

    Indeed.

    Type inferernce has it's place, but don't use it just to make your code look Sexy/LinQy. If you mean a boolean, use a boolean. It makes you're code easier to read, and with more complicated datatypes also means that you get intellisense made available to you...

    Martin.

    Intellisense is exactly the same, var is not like var in VB/javascript in the meaning of variant or something, it just tells the compiler to get the correct type at COMPILE time. So VS will threat the variable the same on the next line if you write bool or var, the tooltip on the var keyword will even show the correct type.



  • Often "var" can be useful in C#, but when I see it used for every single object/variable it makes me cringe. Especially something simple like a boolean type.

    Despite the fact that "var" in this case is essentially the same as "bool" surely it should be good practice to explicitly state the type?



  • IMO this is just a matter of habit. Nothing bad happens if you use var whenever possible. Since I'm currently rather using script languages like JavaScript and Groovy, where you use var resp. def all the time, I took me some time to figure out what exactly annoys you about that innocent looking line.



  • @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?




  • @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type 😉 .



  • @frits said:

    @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type 😉 .

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?



  • @blakeyrat said:

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

    5 will be int by default, .NET has some rules for this (1L will be long, 1U is an uint,...) which is also why can you can have a method that takes any object and when you pass it 5 it will still be an int.
    Can't use null because it can't defer the type then. The quick workaround is to use something like default(type).
    The same stuff is used when creating anonymous types. new { Name = "Test", Age = 24, NullableDate = default(DateTime?) } so we already have it here.



  •  @blakeyrat said:

    @frits said:

    @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type 😉 .

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

    The compiler takes a look on the righthand side of the = There is evaluates the type of the assignment. That is then the type of the new variable. Only works with an assignment and no things like IDisposable d = new StringReader(...)



  • @blakeyrat said:

    @frits said:

    @DaveK said:

    @ammoQ said:

    Nothing bad happens if you use var whenever possible. 

    Doesn't it lose out on strong type-checking?


    No it's still strongly typed.  The var keyword is just syntactic sugar.  I recommend using it all the time, because you never know when you may want to change the type from bool to some other data type 😉 .

    Ok I'm going to ask a stupid question, because the Var keyword is new to me...

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

     The literal 5 is strongly typed, as an int32 I believe, so no ambiguity there.  Initializing a var to null will cause a compilation error.

     



  • @blakeyrat said:

    How does C# tell what the type is supposed to be? I mean, in this case it's a bool because he's setting it to false right away. And I get that with classes it's not an issue because you specify the class name when you instantiate it.

    But what if you set it to something that can be stored by a dozen types, like 5? What if you set it to null, does it assume it's a nullable string or does it just remain some nebulous non-type?

    var a=5 gets the type System.Int32 (5.GetType() gives the same result - Int32 is the default type for integer literals). var a=null is a compile error.

    The exact same feature is part of C++0x, except with "auto" instead of "var".



  • The following restrictions apply to implicitly-typed variable declarations:

    • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

    • var cannot be used on fields at class scope.

    • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);

    • Multiple implicitly-typed variables cannot be initialized in the same statement.

    • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

    You may find that var can also be useful with query expressions in which the exact constructed type of the query variable is difficult to determine. This can occur with grouping and ordering operations.

    The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable<IGrouping<string, Student>>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.

    However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

    Taken from http://msdn.microsoft.com/en-us/library/bb384061.aspx



  • I really don't like var either. I know it's not technically weakly typed, as in Javascript, but it makes it so much more obvious what type it is when you do

    
    MyClass instance = SomeMethodThatReturnsMyClass()
    
    

    as opposed to

    
    var instance = SomeMethodThatReturnsMyClass()
    
    

    Yeah, yeah, Intellisense will help you there, I know. But I still like to be able to figure out what's going on from the source code as much as possible.



  •  Fun fact: This is one of the rare occasions where Visual Basic actually does things well. (The .NET version at least. You want to skip the paragraph about VB6 though, if you value your sanity)



  • The var keyword should ONLY be used with anonymous types....why???? Consider the following:

    class SimpleToy  { public void TurnOn(); }

    class Factory { public static SimpleToy Get() {...} }

    var x= Factory.Get();

    x.TurnOn(); 

    Now replace the Factory to return a nuclear bomb....the code will still compile, but it would have significantly different ramifications.

     



  • @PSWorx said:

     Fun fact: This is one of the rare occasions where Visual Basic actually does things well. (The .NET version at least. You want to skip the paragraph about VB6 though, if you value your sanity)

    Okay, as a self-described VB.NET hater, that is actually pretty neat.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.