Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can assign null? [duplicate]

Possible Duplicates:
How to check if an object is nullable?
Determine if reflected property can be assigned null

How can I properly identify if a variable (or a class member) of given type can take null? More specifically how to handle Nullable<T> since it is not a reference type? Or any other type that may have some weirdo implicit conversion defined on it. My gut feeling is that the only sure way to find out is to try{} catch{} it and see if it blows up... But maybe there are some tricks to it.

like image 970
Ilia G Avatar asked Dec 09 '22 10:12

Ilia G


1 Answers

It's not clear what information you do have about the type in question.

try/catch will do things at execution time, which isn't really what you want.

For a concrete type, you should be able to know just by knowing the variable type. It should be pretty obvious - or if it's not, you've got bigger problems than not knowing about nullity :)

For a generic type, I've found this is quite useful:

if (default(T) == null)

For a Type reference (e.g. if you're using reflection) you could use:

if (!type.IsValueType || Nullable.GetUnderlyingType(type) != null)
like image 165
Jon Skeet Avatar answered Dec 24 '22 11:12

Jon Skeet