String Nullable returns false

Why:

string s = ""; bool sCanBeNull = (s is Nullable); s = null; 

sCanBeNull equals false?

I am writing a code generator and must ensure that all types passed to it are nullable, if not already present.

  //Get the underlying type: var type = field.FieldValueType; //Now make sure type is nullable: if (type.IsValueType) { var nullableType = typeof (Nullable<>).MakeGenericType(type); return nullableType.FullName; } else { return type.FullName; } 

Do I need to explicitly check the string or am I missing something?

+7
c #
source share
4 answers

is indicates whether a particular type or one of this particular type has a value.

Nullable is a generic struct that allows values ​​with null values ​​other than NULL.

string not Nullable

To find out if a type can be null , use the fact that for all such types, the default value is null , while for all other types it is not:

 default(string) == null; // true 
+6
source share

string is a reference type, so it is not Nullable , since it is reserved for value types.

Actually:

 var nullable = new Nullable<string>(); 

Gives a compile-time error.

The string type must be an unimaginable value type in order to use it as the T parameter in the generic type or System.Nullable method

+3
source share

The rational value of System.Nullable is to represent undefined value types using the null keyword. This does not mean that you can check whether it is possible to set some variable to null using someVar is Nullable .

If at compile time you cannot know in advance whether some variable will have a value type or a reference type, you can use:

 !someVar.GetType().IsValueType 

But usually a general argument would be a better approach.

+1
source share

Nullable is just a normal class like MyClass or System.String ( Nullable<T> is a structure, though).

So, if you type:

 class _Nullable {} struct _Nullable<T> {} class Program { static void Main() { string a = ""; Console.Write(a is _Nullable); } } 

You will not be surprised if it returns false correctly?

If you want to check if something is null or not, you can use if(!(a is ValueType))

  string a = ""; Console.Write("a is nullable = {0}", !(a is ValueType)); 

Output: a is nullable = true

0
source share

All Articles