Basics of Converting Nullable Values ​​to a Nullable Type

What are the basics of converting from Nullable to Nullable?

What happens inside the CLR?

- is the value type internally converted to a reference type?

int i = 100;

and int ? i = 7?

- both types of values?

+3
source share
3 answers

Run this to see what int?is the type of value:

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 found that they are very interesting and make some clever uses.

, ? , , . , - HasValue ( )? Nullable< T > , Value - .

0

An int? Nullable<int>, , . .

Nullable MSDN:

[SerializableAttribute]
public struct Nullable<T> where T : struct, new()
+2

int? iis only a shorthand for . Both are truly value types.System.Nullable <int> i

+1
source

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


All Articles