Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is "int?" in C# types

Tags:

c#

types

int

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?

like image 818
prathapa reddy Avatar asked Jul 29 '16 02:07

prathapa reddy


1 Answers

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.

like image 176
DarkMakukudo Avatar answered Oct 13 '22 10:10

DarkMakukudo