Does var keyword in C# cause boxing?

后端 未结 6 1012
余生分开走
余生分开走 2020-12-10 10:05

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

Is that true?

6条回答
  •  再見小時候
    2020-12-10 10:43

    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(n => n)(5);
    

    But that is just identical to:

    object boxedInt = new Func(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.

提交回复
热议问题