简体   繁体   中英

Non-nullable property is null

I have a very simple class Address :

public class Address
{
    public string Name { get; set; }
    public string Country { get; set; }
}

I declared Name as string and NOT as string? , because it should never be null .

Now i have a method where i get an instance of this class as parameter:

public List<Address> SearchAddress(Address search)
{
    ...
    if (!search.Name.Equals(string.Empty))
    {
        temp = query.Where(a => a.Name.Contains(search.Name));
    }
    ...
}

Now my colleague called this method and i got a System.ArgumentNullException because search.Name is null .

If i have a non-nullable int property i get 0 as value if i don't assign anythig to it.

Why is a non-nullable string property null if no value is assigned and not just string.Empty ?

int is a non-nullable value type (ie, a struct ). Value type fields will be initialized to their default value. Eg, int to 0, bool to false, etc. Full list here .

When you want to be able to assign null to value type variables, you can use Nullable<T> where T : struct or, in the case of an int , Nullable<int> / int? .

string , on the other hand, is a reference type . Reference types can be null, and reference type fields will be initialized as null. As such, having a Nullable<string> / string? is not allowed nor would it make sense.

In your case, you'll want to check whether the Name string is null or empty

if (! String.IsNullOrEmpty(search.Name)) { ... }

String can hold null values, its simple as that!

String is a reference type, but is has certain behavior of value type.

Please read this topic : Null strings and empty strings

您可以使用string.IsNullOrEmpty来确定实例是否为Null和空字符串。

string is a reference type and it's null by default. String.empty is equivalent to a double quoted empty string ("") and hence null is not the same as String.empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM