简体   繁体   中英

Is there a more concise way to check for null values than “if(obj == null)”? (C#)

I have a situation where I'm instantiating a number of custom objects based on a JSON file input. However there are some situations where some of the objects won't be instantiated, and therefore will be left as null values.

The typical way to check for null is

if(obj == null)
{
    //do stuff
}

But if I need to check multiple objects for a null value, this quickly gets messy.

I'd like to know if there's a more concise way I could convert the null checks found in the below code into a more concise, less messy version.

I'm working with C#.

List propertyFields = new List();

    PropertyField typeField = GetPropertyType(question);
    PropertyField minLengthField = GetPropertyMinLength(question);
    PropertyField validAnswersField = GetValidAnswers(question);

    if (typeField != null)
    {
        propertyFields.Add(typeField);
    }

    if (minLengthField != null)
    {
        propertyFields.Add(minLengthField);
    }

    if (validAnswersField != null)
    {
        propertyFields.Add(validAnswersField);
    }

As an option, you can write extension method for your propertyFields class. It can look like this one (I suggested propertyFields is List ):

public static void AddWithCheck<T>(this List<T> list, T value) where T: class
{
  if (value != null)
    list.Add(value);
}

You can create an extension method on your list type, ie List . In this extension method, you can check for null and add it to the list if it's not null .

public static class ListExtensions
{
    public static void AddOrIgnore(this List list, object item)
    {
        if (item == null) return;
        list.Add(item);
    }
}

Then in your client code, you use it by propertyFields.AddOrIgnore(typeField); without checking if typeField is null .

One option to consider might be to take advantage of AddRange .

PropertyField typeField = GetPropertyType(question);
PropertyField minLengthField = GetPropertyMinLength(question);
PropertyField validAnswersField = GetValidAnswers(question);

var fieldsToAdd = new List<PropertyField>() { typeField, minLengthField, validAnswersField };
propertyFields.AddRange(fieldsToAdd.Where(z => z != null));

In effect this adds them to a temporary list, and then conditionally adds them to the main list only if the condition ( != null ) is met.

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