Can assign a zero?

Possible duplicates:
How to check if an object is null? Determine if the display property can be set to null

How can I correctly determine if a variable (or class member) of a given type can take null ? More specifically, how to handle a Nullable<T> , since it is not a reference type? Or any other type on which some implicit conversion can be defined. The feeling of my feeling is that the only sure way to find out is to try{} catch{} it and see if it explodes ... But maybe there are some tricks.

+4
source share
4 answers

It is not clear what information you have about the type in question.

try / catch will do something at runtime that you don't want.

For a particular type, you should know just knowing the type of the variable. This should be pretty obvious - or if it isn't, you have more problems than not knowing about the invalidity :)

For a generic type, I found this very useful:

 if (default(T) == null) 

For Type help (for example, if you use reflection) you can use:

 if (!type.IsValueType || Nullable.GetUnderlyingType(type) != null) 
+11
source

Only reference types can actually contain a null reference; special case Nullable<T> - all syntactic sugar; the resulting value is not really null (since Nullable<T> also a value type, so it cannot contain a null reference), it is just Nullable<T> with default(T) as its value and HasValue = false .

So it depends on what you ask.

If you are trying to determine if a type is suitable for assigning code in a < null literal ( Nothing in VB.NET), then this:

  • All reference types
  • Nullable<T>

If you are trying to determine if a type is suitable for maintaining a null reference bona-fide, then this

  • All reference types

Regarding the use of reflection to check for a specific type at runtime, the IsValueType check should be sufficient to get what you need, even if it is the first (just add special code in your code for Nullable<T> ).

+1
source
 bool canBeNull = !type.IsValueType || (Nullable.GetUnderlyingType(type) != null); 
+1
source

Nullable provides the HasValue property, so if you want to check if the value type is null, then just check to see if it provides this property.

0
source

Source: https://habr.com/ru/post/1343194/


All Articles