Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert string value to object property name [duplicate]

Tags:

this is my first time having to do something like this in C#/.NET and somewhat reminds me of what can easily be done in JavaScript using the eval() function or dynamically scripting and generating HTML. I have a string that is taken from user input, lets say string input = "foo". Now I would like to use the value "foo" as the name of the property for an object I have, say cover in such a way:

string input = "foo";
//magic to convert string value to be used
//as a object property name goes here maybe...
var success = cover.foo;

Is there a way in C# that I can do such a thing? Possibly using reflection? I've tried but I always am returned with an object that doesn't really solve my problem.

like image 321
LaRae White Avatar asked Oct 09 '13 15:10

LaRae White


People also ask

How do you assign a value to an object property?

assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target. It returns the target object which has properties and values copied from the target object.

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique.

Can an object property be a string?

Property keys must be strings or symbols (usually strings). Values can be of any type.


1 Answers

Reflection is the right tool:

PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);
like image 71
Mister Epic Avatar answered Sep 20 '22 20:09

Mister Epic