Search code examples
c#nullable

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?


Solution

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