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.
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.
You cannot. Property keys are unique.
Property keys must be strings or symbols (usually strings). Values can be of any type.
Reflection is the right tool:
PropertyInfo pinfo = typeof(YourType).GetProperty("YourProperty");
object value = pinfo.GetValue(YourInstantiatedObject, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With