How to initialize var?

2020-01-24 22:51发布

Can I initialize var with null or some empty value?

11条回答
Fickle 薄情
2楼-- · 2020-01-24 23:13

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.

查看更多
趁早两清
3楼-- · 2020-01-24 23:16

This is the way how to intialize value to var variable

var _myVal = (dynamic)null; 
查看更多
可以哭但决不认输i
4楼-- · 2020-01-24 23:17

Nope. var needs to be initialized to a type, it can't be null.

查看更多
疯言疯语
5楼-- · 2020-01-24 23:21

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
查看更多
爷的心禁止访问
6楼-- · 2020-01-24 23:21

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:

var someDate = !Convert.IsDBNull(dataRow["SomeDate"])
                    ? Convert.ToDateTime(dataRow["SomeDate"])
                    : (DateTime?) null;
查看更多
狗以群分
7楼-- · 2020-01-24 23:23

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:

var dummy =(string)null;

Here compiler can find the type you want so no problem

You can assign some empty values.

var dummy = string.Empty;

or

var dummy = 0;
查看更多
登录 后发表回答