Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between default(int?) vs (int?)null

Tags:

c#

Is there any difference using default(int?) or (int?)null to assign a variable?

Is the same thing?

Or exists some pros and cons to use each way?

like image 668
Raoni Zacaron Avatar asked Nov 04 '16 17:11

Raoni Zacaron


People also ask

What is the difference between nullable int and int?

No difference. int? is just shorthand for Nullable<int> , which itself is shorthand for Nullable<Int32> . Compiled code will be exactly the same whichever one you choose to use.

What is default of nullable int?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .

What is default of a nullable?

The default value of a nullable or other reference type is null while the default value for a long or other value type is 0 (and any other members set to their defaults).


1 Answers

They're exactly the same thing, as is new int?().

If you're just assigning a variable, you normally wouldn't need it at all though. I'd just use:

int? x = null;

for example.

The time I most often need one of these expressions is the conditional operator, e.g.

int y = ...;
int? z = condition ? default(int?) : y;

You can't use null in that scenario as the compiler can't infer the type of the expression. (Arguably that would be a useful addition to the language, mind you...)

like image 136
Jon Skeet Avatar answered Sep 19 '22 16:09

Jon Skeet