Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 397
Toby Avatar asked Jun 16 '17 10:06

Toby


2 Answers

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.

like image 148
Patrick Hofman Avatar answered Nov 20 '22 01:11

Patrick Hofman


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;
like image 44
Dmitry Bychenko Avatar answered Nov 20 '22 01:11

Dmitry Bychenko