Search code examples
c#objectintnullable

Why int can't be null? How does nullable int (int?) work in C#?


I am new to C# and just learned that objects can be null in C# but int can't.

Also how does nullable int (int?) work in C#?


Solution

  • int is a primitive type and only ReferenceTypes (objects) are nullable. You can make an int nullable by wrapping it in an object:

    System.Nullable<int> i;
    

    -or-

    int? i;
    

    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/using-nullable-types