Can I initialize var with null or some empty value?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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.
This is the way how to intialize value to var variable
Nope.
var
needs to be initialized to a type, it can't be null.A
var
cannot be set tonull
since it needs to be statically typed.However, you can use this construct to work around the issue:
I don't know for sure, but from what I heard you can also use
dynamic
instead ofvar
. This does not require static typing.Also, since it was not clear to me from the question if you meant the
var
keyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:But you cannot do this:
Thank you Mr.Snake, Found this helpfull for another trick i was looking for :) (Not enough rep to comment)
Shorthand assignment of nullable types. Like this:
you cannot assign null to a var type.
If you assign null the compiler cannot find the variable you wanted in var place.
throws error:
Cannot assign <null> to an implicitly-typed local variable
you can try this:
Here compiler can find the type you want so no problem
You can assign some empty values.
or