Setting Properties

  • Thread starter Thread starter Guadala Harry
  • Start date Start date
G

Guadala Harry

I want to have my code loop through a DataTable and set properties of an
object inside the loop - without having to know ahead of time which
properties are being set. The DataTable will contain a varying number of
property/value pairs.

So, how can I set properties of an object at runtime - without hard-coding
the property being set?

For example *rather than* this:
myObject.SomeProperty = "SomeValue";

I want something like this:
string PropToSet = "SomeProperty"; // property to set comes from DataTable
myObject(PropToSet) = "SomeValue"; // value comes from DataTable

How can this be done in C#? What is the correct syntax?

Thanks!
 
Guadala,

GH> I want to have my code loop through a DataTable and set properties
GH> of an object inside the loop - without having to know ahead of
GH> time which properties are being set. The DataTable will contain a
GH> varying number of property/value pairs.

What about this?

class Foo {
string prop1;
int prop2;

object this[string name] {
get {
if (name.Equals("Prop1")) return prop1;
else if (name.Equals("Prop2")) return prop2;
else throw new Exception();
}

set {
if (name.Equals("Prop1")) prop1 = (string) value;
else if (name.Equals("Prop2")) prop2 = (int) value;
else throw new Exception();
}
}

string Prop1 {
get { return prop1; }
set { prop1 = value; }
}

int Prop2 {
get { return prop2; }
set { prop2 = value; }
}
}

Perhaps not very sophisticated yet, but I'm sure you can extend it to
something really nice.

HTH,

Stefan
 
Back
Top