tags:

views:

40

answers:

2

how check is property exist? like

if propertyName in obj
{
}

because there is some moments when obj doesn't have such property

A: 

Give a look at the System.Reflection.PropertyInfo class.

Here is a sample usage

using System.Reflection;  // reflection namespace

// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |                                               BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos, delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
        { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

// write property names
foreach (PropertyInfo propertyInfo in propertyInfos) {
    Console.WriteLine(propertyInfo.Name);
}
Lorenzo
+3  A: 

Another approach using reflection is:

        PropertyInfo info = obj.GetType().GetProperty("PropertyNameToFind");

        if (info != null)
        {
            // Property exists in this type...
        }
Mitch Wheat