Is new () mandatory for a NULL variable for a reference type?

If I made a type variable without a reference, say int , nullable, i.e. int? Does this mean that I need to use a constructor before assigning a value?

Usually to initialize a type variable without a reference, I just do

 int foo = 5; 

But if I have a null data type variable without a reference, is it necessary to initialize as shown below, or can I use simple initialization above?

 int? foo = new int(); foo = 5; 
+5
source share
2 answers

No. You do not need to instantiate before assignment. int? is a structure that is created upon appointment.

Your assignment foo = 5; actually:

 foo = new Nullable<int>(5); 

All this is done by the compiler. No need to do it yourself.

+8
source

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

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

we will find the implicit expression of the operator:

 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 calling the constructor explicitly

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

we can use an implicit operator

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

In your particular case, T is int , and we have

 int? foo = 5; 
+2
source

Source: https://habr.com/ru/post/1268903/


All Articles