简体   繁体   中英

Check if object property has an assigned value

I have a class which allows for some properties to be left empty (null) problem is I don't know how to properly check for that and keep getting an error.

This is the class:

public class ZoomListItem
{
    public string image { get; set; }
    public string text1 { get; set; }
    public string text2 { get; set; }
    public ZoomAction action { get; set; }
}

and here is how I use the instance:

@foreach (ZoomListItem item in Model.templates)
{
    var actionUrl = (item.action != null) ? "" : "#";  //error here

The instantiation of the class has not assigned an action value, only text and image are given values. I get the following error in the line of the conditional:

An exception of type 'System.ArgumentException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: Value cannot be null or empty

Am I not checking correctly with item.action != null ?

Your code should check if item.action is null, but does not check if item is null. In the case that item is null, then a null reference exception will occur. You may want:

var actionURL = (item != null && item.action != null) ? "" : "#";

This will check item is not null first and then check item.action is not null.

@Luaan's comment looks like it contains the answer

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