Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method GetProperties with BindingFlags.Public doesn't return anything

Tags:

c#

reflection

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.

like image 796
Nikola Kolev Avatar asked Jul 03 '11 09:07

Nikola Kolev


2 Answers

From the documentation of the GetProperties method:

You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.

like image 101
João Angelo Avatar answered Nov 01 '22 08:11

João Angelo


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);
like image 21
driis Avatar answered Nov 01 '22 08:11

driis