Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String is Nullable returns false

Tags:

c#

.net

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?

like image 914
David Avatar asked Sep 10 '15 10:09

David


People also ask

Are strings Nullable?

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.)

Is string null or empty?

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 .

How do you write a string that is not equal to null in Java?

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 .


1 Answers

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
like image 106
Jon Hanna Avatar answered Oct 17 '22 23:10

Jon Hanna