Thursday, 2 February 2017

Difference between int and int? in c# with example

Int:

--> cannot allow to null values

Int ?:

--> Allows null values

Examples:

    class Program
    {
        static void Main(string[] args)
        {
            //Int a object cannot be null. It doesn't allow null value
            int a = null; (It will thrown a error because. a object cannot hold null value)
            //Int? b object can be null. It allows null value
            int? b = null;
            Console.WriteLine(b);
            Console.WriteLine(a);
        }
    }

Error Message:

Severity    Code    Description    Project    File    Line    Suppression State
Error    CS0037    Cannot convert null to 'int' because it is a non-nullable value type    int vs nullable int .


No comments:

Post a Comment