Basics of conversion of Not nullable to Nullable type
What is the basics of conversion of Not Nullable type to Nullable type?
What happens inside CLR ?
is value type is internally converted to refer开发者_开发百科ence type?
int i = 100;
and int ? i = 7?
is both are value type?
An int?
is the same as Nullable<int>
which is a struct, i.e. a value type. There are no conversions to reference types here.
Here's the definition of Nullable from MSDN:
[SerializableAttribute]
public struct Nullable<T> where T : struct, new()
int? i
is just shorthand for System.Nullable <int>
i
. Both are indeed value types.
Run this to see that the int?
is a value type:
class Program
{
static int? nullInt;
static void Main(string[] args)
{
nullInt = 2;
Console.WriteLine(string.Format("{0} + 3 != {1}", nullInt, DoMath(nullInt , 3).ToString()));
Console.WriteLine(string.Format("{0} * 3 = {1}" , nullInt , DoMultiply(nullInt , 3).ToString()));
nullInt = null;
Console.WriteLine(string.Format("{0} + 3 != {1}" , nullInt , DoMath(nullInt , 3).ToString()));
Console.WriteLine(string.Format("{0} * 3 = {1}" , nullInt , DoMultiply(nullInt , 3).ToString()));
Console.ReadLine();
}
static int? DoMath(int? x , int y)
{
if (x.HasValue)
{
return (++x) + y;
}
else
return y;
}
static int DoMultiply(int? x , int y)
{
if (x.HasValue)
{
return (int)x * y;
}
else
return 0;
}
}
I have found these to be very interesting and makes for some clever uses.
What ?
does is create a nullable reference to an otherwise non-nullable value type. It is like having a pointer that can be checked - HasValue
(a boolean value)? Nice thing about the Nullable< T >
is that the Value
property does not need to be cast to it's original type - that work is done for you inside the nullable struct.
精彩评论