Why does:
string s = "";
bool sCanBeNull = (s is Nullable);
s = null;
sCanBeNull
equate to false?
I'm writing a code generator and need to ensure every type passed to it is nullable, if it isn't already.
//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 have to explicitly check for a string or am I missing something?
In C# 8.0, strings are known as a nullable “string!”, and so the AllowNull annotation allows setting it to null, even though the string that we return isn't null (for example, we do a comparison check and set it to a default value if null.)
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
For any non-null reference value x , x. equals(null) should return false . The way to compare with null is to use x == null and x != null .
is
tells you whether a value is of a particular type, or one derived from that particular type.
Nullable
is a generic struct
that allows for nullable versions of non-nullable values.
string
is not a Nullable
To tell if a type can have null
values 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With