slandau
slandau

Reputation: 24052

c# check if property exists before using it

IndicationBase indication = new IndicationBase(Chatham.Web.UI.Extranet.SessionManager.PhysicalUser);
// check for permissions
LightDataObjectList<TransactionPermission> 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.

Upvotes: 2

Views: 1530

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499760

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 :)

Upvotes: 4

Related Questions