简体   繁体   中英

Best practice for initializing a nullable integer to default value?

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?

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.

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.

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?()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM