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;
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With