How to initialize var?

前端 未结 11 1908
庸人自扰
庸人自扰 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
    

提交回复
热议问题