开发者

c# check if property exists before using it

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜