How to initialize var?
Asked Answered
P

12

75

Can I initialize var with null or some empty value?

Planogamete answered 25/5, 2010 at 12:47 Comment(6)
Do you mean the C# keyword var or do you mean variables in general?Sheikdom
I want the variable to perform a linq query after initiizationPlanogamete
why not initialize it when you use it?Incandescence
No the var initialization is above if statement which will execute the query based on the condition and will use the same variablePlanogamete
assign (dynamic) null; refer: https://mcmap.net/q/270358/-initialize-var-to-nullAzole
var abc = (dynamic)null; This is how you can do in C#Grieve
I
75

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.

Improvvisatore answered 25/5, 2010 at 12:57 Comment(0)
D
54

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

var foo = new { }; //anonymous type

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 than new object(). You can only reassign the anonymous type to foo 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.

dynamic foo = null;
//or
var foo = (dynamic)null; //overkill

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;

var foo = (T)null;

So your options are:

//initializes to non-null; I like it; cant be reassigned a value of any type
var foo = new { }; 

//initializes to non-null; can be reassigned a value of any type
var foo = new object();

//initializes to null; dangerous and finds least use; can be reassigned a value of any type
dynamic foo = null;
var foo = (dynamic)null;

//initializes to null; more conventional; can be reassigned a value of any type
object foo = null;

//initializes to null; cannot be reassigned a value of any type
var foo = (T)null;
Doe answered 16/1, 2014 at 10:37 Comment(3)
Good list of options. +1Viaticum
Why is dynamic foo = null; dangerous?Richards
@christian, I don't remember what I had in mind then, but in vast majority of the cases object foo = null will do. If you are really trying to intialize a dynamic variable, then fine, just would lose compile time safety.Doe
V
49

This is the way how to intialize value to var variable

var _myVal = (dynamic)null; 
Vaginal answered 9/8, 2016 at 8:33 Comment(0)
T
35

Why wouldn't this be possible?

var theNameOfTheVar = (TheType)null;

eg:

var name = (string)null;

Simple as that.

Thong answered 25/5, 2010 at 12:51 Comment(6)
This is certainly a working solution, but I really can't come up with any reason to use it.Eonism
There is none. I'm just answering the TS' question :)Thong
it's very useful not directly for the var but for properties of an anonymous type like var anonType = new{ Example = (TheType) null};Flowering
@Fredrik Mörk In my case, this helped me in unit tests - if you expect null: var expected = (string)null;Aeneas
This is the correct answer, works flawlessly on older versions such as 7. No errors while compiling assigning it later.Squamous
I get a CS8600 warning "Converting null literal or possible null value to non-nullable type." when I do this with nullable reference types enabled. The warning disappears if you cast null to nullable type, i.e. var name = (string?)null;.Avrom
A
9

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
Abductor answered 25/5, 2010 at 12:49 Comment(1)
thanks for the explanation SomeClass c = null; works perfectly.Midwifery
U
5

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

Undertow answered 25/5, 2010 at 12:49 Comment(1)
Ding! Var is kind of like saying to the compiler "I don't feel like declaring this but you'll know" ... saying var whatever = null is like doing a headfake.Turkmen
E
5

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

var v = new object();
Efrenefron answered 11/11, 2013 at 19:23 Comment(0)
O
4

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.

Ontogeny answered 25/5, 2010 at 12:50 Comment(0)
I
3

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;
Iveson answered 25/5, 2010 at 12:51 Comment(0)
J
0

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.

Joung answered 25/5, 2010 at 12:51 Comment(0)
O
0

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;
Obeng answered 6/8, 2014 at 8:41 Comment(0)
J
0

How about default keyword?

var foo = default(SomeClass);

Compiler doesn't lose what type the foo has. foo will have default value of reference type, null

Jeb answered 17/1, 2023 at 7:32 Comment(3)
Although this would be an answer to his question, I think it would not be desirable to allow such practices to be in your code. this would be the same as saying SomeClass foo = null;Ser
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Ser
@Ser I totally agree with you. I would just avoid this kind of case during coding myself.Jeb

© 2022 - 2024 — McMap. All rights reserved.