user1438082
user1438082

Reputation: 2748

detect error while searching for object name that does not exist

In the code below when MyGlobals.ListOfItemsToControl[i].sItemName does not exist in the object HWRes.HWResObj, I want to detect this issue without jumping to the catch statement.

How can I accomplish this?

try
{
    String HWTemp = "";
    // Ref http://stackoverflow.com/questions/15628140/c-sharp-eliminate-switch-requirement
    HWTemp = HWRes.HWResObj.GetType().GetProperty(MyGlobals.ListOfItemsToControl[i].sItemName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(HWRes.HWResObj, null).ToString();


 // Somehow here I should detect if the value MyGlobals.ListOfItemsToControl[i].sItemName does not exist in the object HWRes.HWResObj
// Detect issue without jumping to catch

}
catch
{
    // I dont want to go here when MyGlobals.ListOfItemsToControl[i].sItemName does not exist in the object HWRes.HWResObj
    .....
}

Upvotes: 0

Views: 64

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149030

Check the return value from GetProperty like this:

var property = HWRes.HWResObj.GetType().GetProperty(MyGlobals.ListOfItemsToControl[i].sItemName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (property != null)
{
    string HWTemp = property.GetValue(HWRes.HWResObj, null).ToString();
}
else
{
    // property does not exist
}

Upvotes: 2

Related Questions