Answered by:
Type dynamic along with Variables

Question
-
I wanted to achieve following requirement not by using reflection
class Customer { public string Name {get;set;} public void Show() { } } Main Program ------------- string propName = "Name" string functionName ="Show" dynamic person = new Customer(); person.propName = "Some Value" person.functionName() How do i achieve it ?
K K Sanghi
Thursday, May 1, 2014 12:46 PM
Answers
-
You must use reflection to be able to get or set the value of a property by specifying its name dynamically. Declaring a type as dynamic doesn't change this. In fact, a dynamc type is actually a static type but it bypasses static type checking at compile time. At runtime, it will behave just like a Customer variable in your example and you will get a runtime exception as you are basically trying to assing a value to a non-exiting property called "propName" of the Customer class.
Reflection is the only way to go here unless you set the property using usual property syntax, i.e.:
person.Name = "Some Value";
Another option for you may be to use an IDictionary to store the values in the class instead of using properties.
- Marked as answer by Herro wongMicrosoft contingent staff Thursday, May 8, 2014 6:42 AM
Thursday, May 1, 2014 2:11 PM
All replies
-
You must use reflection to be able to get or set the value of a property by specifying its name dynamically. Declaring a type as dynamic doesn't change this. In fact, a dynamc type is actually a static type but it bypasses static type checking at compile time. At runtime, it will behave just like a Customer variable in your example and you will get a runtime exception as you are basically trying to assing a value to a non-exiting property called "propName" of the Customer class.
Reflection is the only way to go here unless you set the property using usual property syntax, i.e.:
person.Name = "Some Value";
Another option for you may be to use an IDictionary to store the values in the class instead of using properties.
- Marked as answer by Herro wongMicrosoft contingent staff Thursday, May 8, 2014 6:42 AM
Thursday, May 1, 2014 2:11 PM -
Let me be specific
I want to use variable names as
person.VariableName = "Some Value"
K K Sanghi
Thursday, May 1, 2014 2:13 PM -
Let me be specific
I want to use variable names as
person.VariableName = "Some Value"
K K Sanghi
As I have already mentioned, you cannot to this in C#.
You will have to use reflection.
Thursday, May 1, 2014 2:29 PM