开发者

c# check if property exists before using it

开发者 https://www.devze.com 2023-02-07 07:45 出处:网络
IndicationBase indication = new IndicationBase(Chatham.Web.UI.Extranet.SessionManager.PhysicalUser); // check for permissions
IndicationBase indication = new IndicationBase(Chatham.Web.UI.Extranet.SessionManager.PhysicalUser);
// check for permissions
LightDataObjectList<TransactionPermiss开发者_如何学Cion> perms = indication.Model.Trx.TransactionPermissionCollection;

So sometimes the indication will have a Model.Trx.TransationPermissionCollection, and a lot of times it won't. How do I check to see if it does before trying to access it so I don't get an error.


Presumably you're getting a NullReferenceException? Unfortunately there's no nice short cut for this. You have to do something like:

if (indication.Model != null &&
    indication.Model.Trx != null)
{
    var perms = indication.Model.Trx.TransactionPermissionCollection;
    // Use perms (which may itself be null)
}

Note that the property itself always exists here - static typing and the compiler ensure this - it's just a case of checking whether you've got non-null references everywhere in the property chain.

Of course, if any of the properties are non-nullable types, you don't need to check those for nullity :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号