Method GetProperties with BindingFlags.Public doesn't return anything
Solution 1
From the documentation of the GetProperties
method:
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
Solution 2
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);
Nikola Kolev
Team player with great positive influence on people and strong leadership skills. Believes in an "one for all and all for one" vision for building a team. Software engineer with 10 years experience. Java enthusiast with tons of knowledge in back-end and recently in cutting-edge front-end as well. A reliable professional used to work under pressure with enthusiastic "can-do" attitude focused on delivering high quality products.
Updated on August 31, 2022Comments
-
Nikola Kolev over 1 year
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 theContact
(source) to the newly instantiatedContactBO
(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
andsourceProps
have lengths of zero.But when I expand the
GetProperties
method withBindingFlags.Instance
, it suddenly returns everything. I would appreciate if someone could shed light on that matter because I'm lost. -
Nikola Kolev almost 13 yearsThat's exactly what I'm doing. The reason for the question was why BindingFlags.Public does not return the public properties? Well I guess this is how the framework is working.