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

StackOverflow https://stackoverflow.com/questions/21232948

  •  30-09-2022
  •  | 
  •  

質問

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?

役に立ちましたか?

解決

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.

他のヒント

Nullable<T> is defined as:

public struct Nullable<T> where T : struct

meaning: it only works on value-type T (excluding Nullable<TSomethingElse> itself).

You cannot use Nullable<T> on reference-types (or on Nullable<T>), but you don't need to since all reference-types (including object and string) are already "nullable", in that you can assign null to them.

string and object are reference types, and therefore are "nullable" already. The Nullable<T> type exists as a wrapper around value types that don't support null out of the box.

string myString = null //fine
int myInt = null //compiler error
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top