Search code examples
c#nullable

Why string or object type don't support nullable reference type?


Look into following code block:

//Declaring nullable variables.
//Valid for int, char, long...
Nullable<int> _intVar;
Nullable<char> _charVar;

//trying to declare nullable string/object variables
//gives compile time error. 
Nullable<string> _stringVar;
Nullable<object> _objVar;

While compiling code compiler gives following error message:

The type 'string'/'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

I read it several times but still unable to understand. Can anyone clarify this? Why object or string dont support nullable reference type?


Solution

  • object and string are reference types, so they're already nullable. For example, this is already valid:

    string x = null;
    

    The Nullable<T> generic type is only for cases where T is a non-nullable value type.

    In the declaration for Nullable<T> there is a constraint on T:

    public struct Nullable<T> where T : struct
    

    That where T : struct is precisely the part that constrains T to be a non-nullable value type.