Search code examples
c#typesint

what is "int?" in C# types


I've seen this code sample question in a exam and it works perfectly.

namespace Trials_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int? a = 9;
            Console.Write("{0}", a);
        }
    }
}

But the below code throws an error CS0266.

namespace Trials_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int? a = 9;
            int b = a;
            Console.Write("{0},{1}", a, b);
        }
    }
}

Can somebody explain me in detail?


Solution

  • This is a C# nullable types

    Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

    This line int b = a; throws an error because you cannot directly assign an int type into a nullable int type. In other words, int datatype cannot accept null value.