Reputation: 29311
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?
Upvotes: 5
Views: 4779
Reputation: 144136
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?()
Upvotes: 0
Reputation: 25351
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.
Upvotes: 0
Reputation: 283713
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.
Upvotes: 6