Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable.GetUnderlyingType(string) returns null

Tags:

c#

Nullable.GetUnderlyingType(string) returns null

I think this is because string is a reference type, should this not work though for built in types which string is?

To Expand on my question, If you call

Nullable.GetUnderlyingType(int) 

You get nothing back as int is not nullable

if you call

 Nullable.GetUnderlyingType(int?) 

a result is returned as it is a nullable type

But a string by default is nullable as it is a reference type, but is also a built in type so I was expecting

Nullable.GetUnderlyingType(string) 

to return something as it is nullable

like image 805
Lord Darth Vader Avatar asked Oct 19 '25 07:10

Lord Darth Vader


1 Answers

So according to the MSDN for Nullable.GetUnderlyingType, the return type for it is:

"The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null."

So what is a closed generic nullable type? A great explanation can be found here from Mehrdad(here).

From his post:

"All types can be classified as either open types or closed types. An open type is a type that involves type parameters. More specifically:

A type parameter defines an open type. An array type is an open type if and only if its element type is an open type. A constructed type is an open type if and only if one or more of its type arguments is an open type. A constructed nested type is an open type if and only if one or more of its type arguments or the type arguments of its containing type(s) is an open type. A closed type is a type that is not an open type."

So for an example:

Closed generic nullable type = List<string>

Open generic type = List<T>

UPDATED:

Thanks to Kiziu's comments and clarification I have updated my answer.

Nullable.GetUnderlyingType

The only case where a value other than null will be returned is when the type is of typeof(Nullable<>). Nullable<> is a struct, which means it cannot inherited. So since string isn't of type Nullable<>, it will return null. Where as data types like int?, double? that are of type Nullable<> will return their underlying types.

like image 61
A.sharif Avatar answered Oct 21 '25 22:10

A.sharif