tags:

views:

695

answers:

6

My boss forbide me to use var as it would cause boxing and slowing down the app.

Is that true?

+26  A: 

Why are so many people cursed with bosses who are dumb? Revolution, brothers!

Your boss needs to read the documentation. var causes the compiler to figure out the variable type by looking at the static type of the initialization expression. It doesn't make the slightest difference at runtime whether you specify the type by hand or you use var and let the compiler figure it out for you.

Update In a comment under the question, Hans Passant asks

can you think of any var initializer that causes boxing without using a cast?

An example of a self-contained expression that forces such a conversion is:

var boxedInt = new Func<int, object>(n => n)(5);

But that is just identical to:

object boxedInt = new Func<int, object>(n => n)(5);

In other words, this doesn't really have anything to do with var. The result of my initializer expression is object, hence var has to use that as the type of the variable. It couldn't be anything else.

Daniel Earwicker
Well, the type inferer could, in theory, interfere a boxed type for a literal. But I guess it doesn't. ++ for rant.
delnan
Even if it did the boss is guilty of micro-optimisation, and even if that wasn't true he's guilty of favouring performance over maintenance which is almost universally wrong. Why are the people in charge always the ones who don't know what they're talking about?
annakata
@delnan: What would be the reason for doing so?
Brian Rasmussen
@annakata: It's called "the Peter principle": http://en.wikipedia.org/wiki/Peter_Principle
Fredrik Mörk
I'm not defending the bullshit by OP's boss in anyway, I'm just nitpicking :)
delnan
@Fredrik: "in time, every post tends to be occupied by an employee who is incompetent to carry out their duties" awesome stuff, thanks for link
annakata
Even simpler than the Peter Principle is the recursive proof: if your boss is stupider than you, why was he hired? Well, his boss is stupider than him. And so on.
Daniel Earwicker
DISCLAIMER. I am not referring to my present employers! (If anything I have the opposite problem, I'm cursed with a smart boss).
Daniel Earwicker
@Daniel: Stop sucking up to your boss :-) Is he reading Stackoverflow? ;-)
Steven
Oh, he doesn't need to - *that's* how smart he is! (Okay, I think I'm out of this hole now...)
Daniel Earwicker
@delnan - I think you may be thinking of Java and how they have named boxing classes like `Integer`, etc. In C# the universal boxing type is `object`, and any type inference engine worth its salt is going to have to do better than that.
Daniel Earwicker
+19  A: 

That's not true at all.

var just means "dear compiler, I know what the type is, and so do you, so let's just move on shall we."

It makes the code shorter and some find this more readable (others find it less readable), but there's no performance penalty whatsoever.

Brian Rasmussen
"dear compiler..." nice :) But point of order I think it means "Dear compiler I don't care what the type is, you decide"
annakata
@annakata: "you decide" is fine too, as long as "surprise me!" is out of the question :)
Brian Rasmussen
If the interfered type (provided it is correct, of course) surprises you, you should propably take a closer look - at least in Haskell (only type-interfering language I ever used) it usually means you messed something up.
delnan
@delnan fair enough, there are cases where it may not be evident, but I wouldn't want to define the meaning of `var` as "surprise me!"
Brian Rasmussen
Yeah, of course that's not its meaning.
delnan
I tend not to use `var`, unless 1. The type is absolutely clear (for instace: `var customer = new Customer();’`), or 2. the type cannot be written, because it is anonymous, or 3. In cases where ‘I believe’ the type is obvious enough. Example of this last point: I for instance tend to use `var` for the result of LINQ queries, where the type is an `IEnumerable<T>` or `IQueryable<T>`. I use these queries often in small methods that return a T[] and in that case I find `var` clear enough. In all other situations, I write out the type.
Steven
@annakata: No, it doesn't mean "I don't care what the type is" - it means "I want the type to be the type of the expression on the right hand side of =". There's no guessing involved. The compiler isn't at liberty to choose a type arbitrarily. The specification lays it down very clearly.
Jon Skeet
@Jon: perhaps I spoke too lightly. I'm not suggesting the compiler guesses or that there's any kind of uncertainty here, I'm trying to express that var allows me to not care about the type of the LHS except in terms of what the RHS gives me, *whatever that may be*. The value is in the decoupling to me.
annakata
@annakata: Right, in that sense it's reasonable. I just don't want anyone to think it's ambiguous :)
Jon Skeet
@Steven - 3. When I have a stupidly long type, e.g. `Dictionary<String,List<KeyValuePair<MyNamespace.MyType1,MyNamespace.MyType1>>>` and don't have it aliased with a `using`
ck
@ck: I agree. I tend to use `var` in this situation. While it hides the type and makes the code less understandable, it improves readability a lot. I think this is a good case.
Steven
@Steven - I use var aggressively, and there's certainly a discussion to be had (and indeed plenty around already) about the conceptual value of var - but I assert that expressing a type != clarity and not needing to know is the point - it doesn't matter what the thing is but how I use it. It's almost duck typing.
annakata
@Annakata: Perhaps this is a matter of taste. I know in the functional world (Lisp, F#) they don't care about types. However, I often find it very useful in my C# applications to understand what the type is. Leaving out the type could mislead the user, because he has to figure it out himself. But I think that in many situations, a very well written program should perhaps not really need the types to be explicitly shown. Perhaps the problem is, that I'm not that good of a programmer ;-)
Steven
+37  A: 

An approach that might work is to write these two methods:

public static void WithInt()
{
    int x = 5;
    Console.WriteLine(x);
}

public static void WithVar()
{
    var x = 5;
    Console.WriteLine(x);
}

Compile, and use ildasm to examine the produced CIL. Show your boss.

edit @ck has done all but the last step for you :)

AakashM
+1 for IL proofs
annakata
+1 for being able to show his boss that he is wrong
Spooks
There goes your raise.... :(
ChaosPandion
Ha, or how about just hover the mouse over `x` (in Visual Studio) and show the boss that it says "int"?
Dan Tao
I suggest some sensitivity when presenting this "in your face!" evidence to your boss - he may genuinely have confused this issue with something else and demonstrating his wrongness won't win favours with him IMO.
JBRWilkinson
I propose more "in your face!"-ness towards bosses in general - the more they get used to it the more acceptable it becomes for the rest of us. And it's funnier.
annakata
Yea, let me know how your termination goes after you tell your boss he/she is wrong.
PSU_Kardi
Well I said my boss today var is not boxing he is wrong! He said:"really ah ok". Then he saw my code:foreach(var item in ItemsList){}telling me now to replace the var with the proper type like string. :P
msfanboy
+22  A: 

Following on from Aakash's answer, here is the IL: (thanks LINQPad)

WithInt:
IL_0000:  ldc.i4.5    
IL_0001:  stloc.0     
IL_0002:  ldloc.0     
IL_0003:  call        System.Console.WriteLine
IL_0008:  ret         

WithVar:
IL_0000:  ldc.i4.5    
IL_0001:  stloc.0     
IL_0002:  ldloc.0     
IL_0003:  call        System.Console.WriteLine
IL_0008:  ret      
ck
Wait...what is that difference I see? Oh nevermind, that was just a spot on my monitor :)
Brian Gideon
Hehe.. nice :-)
ck
A: 

Conceptually, I wouldn't trust var either. I don't really want my variables to also have a variable type; that's just begging for disaster.

CSpangled
Please read the C# spec. 'var' in c# is not a dynamic declaration, but an inferred static type.
Steve Mitcham
I hope this is sarcasm. Html codes don't show properly on here, so you can't just write `</sarcasm>`.
ck
gotta be kidding
Felipe Lima
+7  A: 

Maybe your boss is an old Visual Basic (as in <= 6.0) programmer used to the VARIANT type. If you didn't specify the type of your variable explicitly in your DIM statement, it was a VARIANT which is a sort of union if I recall correctly. You could view this as a sort of "boxing" and "unboxing" when passing such variables to functions.

Sometimes people get confused. Ask your boss about his Visual Basic war stories. Listen, learn and earn some sympathy at the same time! As you leave the office you could point out that the c# compiler figures this stuff out at compile time and that "boxing" isn't an issue anymore.

Don't expect your boss to have to keep up with the newest changes to languages/APIs. This isn't about being dumb. It's about having other stuff to do. His job, for instance.

Edit: As noted in comments below, though, telling you not to use var for the wrong reasons is probably not his job...

Daren Thomas
+1 for explaining the bosses's behaviour. It sounds quite likely. But if the boss thinks his knowledge stays relevant without him keeping up, then he is at least a bit dumb. And if he spends his time telling programmers which keywords to use (although they know better than he does), then he isn't doing his job, either.
nikie
I don't kow. I think it is reasonable to expect your boss to be educated on the platforms in use at your company especially if he is dictating how you use those platforms.
Brian Gideon
@Brian - Exactly. If you're going to dictate keywords, you'd better know what you're talking about. If you don't want to keep up on the latest technical developments, that's fine, but don't micromanage to the point of dictating what keywords are acceptable.
Joel Mueller