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
var
just tells the compiler to infer the type you wanted at compile time...it cannot infer fromnull
(though there are cases it could).So, no you are not allowed to do this.
When you say "some empty value"...if you mean:
Then yes, you may do that, but not
null
.Well, I think you can assign it to a new object. Something like:
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,
the compiler cannot resolve this because there's no type bound to null. You can make it like this.
This will work because now x can know its type at compile time that is string in this case.
Why wouldn't this be possible?
eg:
Simple as that.
Well, as others have stated, ambiguity in type is the issue. So the answer is no, C# doesn't let that happen because it's a strongly typed language, and it deals only with compile time known types. The compiler could have been designed to infer it as of type
object
, but the designers chose to avoid the extra complexity (in C#null
has no type).One alternative is
Again note that you're initializing to a compile time known type, and at the end its not
null
, but anonymous object. It's only a few lines shorter thannew object()
. You can only reassign the anonymous type tofoo
in this one case, which may or may not be desirable.Initializing to
null
with type not being known is out of question.Unless you're using
dynamic
.Of course it is pretty useless, unless you want to reassign values to
foo
variable. You lose intellisense support as well in Visual Studio.Lastly, as others have answered, you can have a specific type declared by casting;
So your options are: