5

I ran into some code which is setting a nullable integer like so:

int? xPosition = new int?();

This was an unfamiliar syntax for me. I would've expected either of these forms:

int? xPosition = null;
int? xPosition = default(int?);

Are there any functional differences between these three variable declarations?

Sean Anderson
  • 27,963
  • 30
  • 126
  • 237
  • God forbid duplicates actually get closed as duplicates when people could just be repeating the exact same answer to get more Imaginary Internet Points for accomplishing nothing... – Servy Sep 07 '16 at 18:04

3 Answers3

6

No functional difference. All three must instantiate an int?, and then since the default is HasValue == false, none of them require a subsequent member assignment.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

In your examples the best way to do it is:

int? xPosition = null;

However, in different scenarios, the other ways can be better, or even the only possibility. For example, in code that receives data of different types, default is the way to go because the default value depends on the type and it is not always null. For example, if some code may receive int or int?, then you don't know whether the default is zero on null, so using default guarantees that you will get the correct default value.

An example of such scenario can is when using LINQ.

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
0

These are all equivalent according to the specification:

4.1.10 Nullable types

An instance for which HasValue is false is said to be null. A null instance has an undefined value

4.1.2 Default constructors

All value types implicitly declare a public parameterless instance constructor called the default constructor. The default constructor returns a zero-initialized instance known as the default valuefor the value type:

• For a struct-type, the default value is the value produced by setting all value type fields to their default value and all reference type fields to null.

nullable types are structs and HasValue is a bool with a default value of false so new int?() is null.

5.2 Default values

The default value of a variable depends on the type of the variable and is determined as follows:

• For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§4.1.2).

so default(int?) is equivalent to new int?()

Lee
  • 142,018
  • 20
  • 234
  • 287