Reputation: 5107
I need to set all of the properties of a class using the same function. Currently I am using reflection to get all of the properties and looping through to set their values. I know all of the properties, there is nothing dynamic happening.
Here is my code I am currently running in my constructor:
foreach (PropertyInfo property in this.GetType().GetProperties())
{
// retreive the value and set it
property.SetValue(this, GetValue(field), null);
}
Is there way to do something similar without using reflection?
Upvotes: 1
Views: 185
Reputation: 9124
Not that I am aware of based on the information given here.
That said, it does beg the question what are you doing that would require you to do this? Why do you need to iterate over all your properties in a loop anyway, how many do you have?
A bit more detail may prompt someone to give you a better solution. For example, what are the properties doing? Are they connected to some underlying data that could be changed without using reflection? Is having a bunch of discrete properties the way to go if you have a lot of them?
Upvotes: 4
Reputation: 29538
Um, maybe I'm misinterpreting what you are saying, but you said you know all the properties, why not just write a method to set them?
void SetValues() {
this.Property1 = field1;
this.Property2 = field2;
this.Property3 = field3;
this.Property4 = field4;
}
I suspect there is something missing from your question.
Upvotes: 1