Hi,
I have an object that has a number of properties. I have to add a
variable to the correct property at runtime (not compile time).
Problem is I do not know which one to add it to (if you see what I
mean). How do I do this at runtime. My system will return the name of
the property at runtime as follws:
propName = Some process that generates the at runtime;
objectName.propName = "some variable generated at runtime";
I agree with Jeff, your question is hard to understand. The phrase "add
a variable" doesn't make much sense, given your pseudo-code example.
Nor does "variable generated at runtime" in any case. But, let's see if
we can figure it out.
Perhaps you simply mean "assign a value to" instead, where you have
something like this:
class TestClass
{
public string TestProperty { get; set; }
}
Then some code like this:
TestClass test = new TestClass();
string strProperty = "TestProperty";
string strNewValue = "some new value to assign to the property";
test.«something to resolve strProperty as an actual property here»
= strNewValue;
With the end result that the "TestProperty" property of the "test"
instance now contains the value "some new value to assign to the property".
Is that correct?
If so, then the simple answer is that you use reflection (see
Type.GetProperty() and PropertyInfo.SetValue() methods). But in
reality, that's a very poor, hard-to-maintain, inefficient way to manage
your data structure.
More typically, if you have this need for dynamic maintenance of values
by some name, you'd use a dictionary to store the values. IMHO that's a
much better choice. But if you can describe more precisely what you're
trying to do and why you think that having a named property that you
access dynamically is an important feature to implement, it's possible
someone could provide a more specific, useful suggestion.
And if my interpretation isn't correct, you really need to take more
time and write your question so that it's clear and unambiguous.
Pete