Raoni Zacaron Raoni Zacaron - 1 year ago 119
C# Question

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

Is there any difference using

to assign a variable?

Is the same thing?

Or exists some pros and cons to use each way?

Answer Source

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...)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download