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.
From the documentation of the GetProperties
method:
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With