Alex Rivera | Logout

Method GetProperties with BindingFlags.Public doesn't return anything

Asked 2011-07-03T09:06:06.830
43

Probably a silly question, but I couldn't find any explanation on the web.
What is the specific reason for this code not working? The code is supposed to copy the property values from the Contact (source) to the newly instantiated ContactBO (destination) object.

public ContactBO(Contact contact)
{
    Object source = contact;
    Object destination = this;

    PropertyInfo[] destinationProps = destination.GetType().GetProperties(
        BindingFlags.Public);
    PropertyInfo[] sourceProps = source.GetType().GetProperties(
        BindingFlags.Public);

    foreach (PropertyInfo currentProperty in sourceProps)
    {
        var propertyToSet = destinationProps.First(
            p => p.Name == currentProperty.Name);

        if (propertyToSet == null)
            continue;

        try
        {
            propertyToSet.SetValue(
                destination, 
                currentProperty.GetValue(source, null), 
                null);
        }
        catch (Exception ex)
        {
            continue;
        }
    }
}

Both classes have the same property names (the BO class has a few other but they don't matter on initialization). Both classes have only public properties. When I run the example above, destinationProps and sourceProps have lengths of zero.

But when I expand the GetProperties method with BindingFlags.Instance, it suddenly returns everything. I would appreciate if someone could shed light on that matter because I'm lost.

Edit
Report

1 Answer

34

This behaviour is because you must specify either Static or Instance members in the BindingFlags. BindingFlags is a flags enum that can be combined using | (bitwise or).

What you want is:

.GetProperties(BindingFlags.Instance | BindingFlags.Public);
answered 2011-07-03T09:11:02.250

Your Answer