Toby
Toby

Reputation: 10154

Is new() required for nullable non-reference type variable?

If I have made a variable of a non-reference type, say int, nullable, i.e. int?, does this mean I need to use a constructor before assigning a value?

Normally to intialise a non-reference type variable I simply do

int foo = 5;

But if I have a nullable non-reference data type variable is initialisation neccessary, as below, or can I still use the simple initialisation above?

int? foo = new int();
foo = 5;

Upvotes: 5

Views: 110

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

int? is a syntax sugar for Nullable<int>; as for Nullable<T> if we have look at its implementation

https://referencesource.microsoft.com/#mscorlib/system/nullable.cs,ffebe438fd9cbf0e

we'll find an implicit operator declaration:

public struct Nullable<T> where T : struct
{
     ...

     [System.Runtime.Versioning.NonVersionable]
     public static implicit operator Nullable<T>(T value) {
         return new Nullable<T>(value);
     }

     ...
}

So for any struct T instead of explicit constructor call

T value = ...

T? test = new Nullable<T>(value);

we can use implicit operator

T? test = value; // implicit operation in action

In your particular case T is int and we have

int? foo = 5;

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157098

No. You don't need to create an instance before assignment. The int? is a struct which is created on assignment.

Your assignment foo = 5; is actually:

foo = new Nullable<int>(5);

This is all done by the compiler. No need to do this by yourself.

Upvotes: 8

Related Questions