reference all properties of a class within the constructor

G

Guest

Is it possible to reference all the public properties that are in a class
within that class's constructor using REFLECTION, and then reference them
with a string variable?
I have a class that will have 35 integer values as public properties that
must be read in from a database. Also, each property of this class will have
the same name as the column name from the dbase table. For that reason, I
would like to just set up a loop to get the property name from the GetName
property in the DataReader, and then assign the value from the read field.
Otherwise I will have to assign each property from the table individually.
 
N

Nicholas Paldino [.NET/C# MVP]

Ric,

Absolutely, here is how you would do it:

// Get all the fields in the class, and map them to the field name.
FieldInfo[] fields = this.GetType().GetFields();

// Cycle through the fields, and add them to a hashtable.
Hashtable map = new Hashttable();

// Cycle.
foreach (FieldInfo fieldInfo in fields)
{
// Add to the hashtable.
map.Add(fieldInfo.Name, fieldInfo);
}

// Make the database call. As you cycle through the fields, you would get
the field info, and set the value.
((FieldInfo) map["column"]).SetValue(this, value);

Hope this helps.
 
J

Jon Skeet [C# MVP]

Ric#k said:
Is it possible to reference all the public properties that are in a class
within that class's constructor using REFLECTION, and then reference them
with a string variable?
I have a class that will have 35 integer values as public properties that
must be read in from a database. Also, each property of this class will have
the same name as the column name from the dbase table. For that reason, I
would like to just set up a loop to get the property name from the GetName
property in the DataReader, and then assign the value from the read field.
Otherwise I will have to assign each property from the table individually.

Well, you can get all the properties using Type.GetProperties, or get
the property for a particular name using Type.GetProperty. You can then
set or get their values. Which part are you having trouble with?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top