How to initialize var?

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

Can I initialize var with null or some empty value?

相关标签:
11条回答
  • 2020-11-27 16:09

    A var cannot be set to null since it needs to be statically typed.

    var foo = null;
    // compiler goes: "Huh, what's that type of foo?"
    

    However, you can use this construct to work around the issue:

    var foo = (string)null;
    // compiler goes: "Ah, it's a string. Nice."
    

    I don't know for sure, but from what I heard you can also use dynamic instead of var. This does not require static typing.

    dynamic foo = null;
    foo = "hi";
    

    Also, since it was not clear to me from the question if you meant the varkeyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:

    string s = null; // reference
    SomeClass c = null; // reference
    int? i = null; // nullable
    

    But you cannot do this:

    int i = null; // integers cannot contain null
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 16:15

    var just tells the compiler to infer the type you wanted at compile time...it cannot infer from null (though there are cases it could).

    So, no you are not allowed to do this.

    When you say "some empty value"...if you mean:

    var s = string.Empty;
    //
    var s = "";
    

    Then yes, you may do that, but not null.

    0 讨论(0)
  • 2020-11-27 16:21

    you can't initialise var with null, var needs to be initialised as a type otherwise it cannot be inferred, if you think you need to do this maybe you can post the code it is probable that there is another way to do what you are attempting.

    0 讨论(0)
  • 2020-11-27 16:25

    Well, I think you can assign it to a new object. Something like:

    var v = new object();
    
    0 讨论(0)
提交回复
热议问题