How to initialize var?

前端 未结 11 1919
庸人自扰
庸人自扰 2020-11-27 15:29

Can I initialize var with null or some empty value?

11条回答
  •  不知归路
    2020-11-27 16:10

    C# is a strictly/strongly typed language. var was introduced for compile-time type-binding for anonymous types yet you can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.

    When you say,

    var x = null; 
    

    the compiler cannot resolve this because there's no type bound to null. You can make it like this.

    string y = null;
    var x = y;
    

    This will work because now x can know its type at compile time that is string in this case.

提交回复
热议问题