In other languages like JavaScript I can use for example:
const obj = { a: 5 };
obj["a"] //returns 5
Is it possible to get an object property if it's name is given as string in C#? I don't want a giant if/else tree
In other languages like JavaScript I can use for example:
const obj = { a: 5 };
obj["a"] //returns 5
Is it possible to get an object property if it's name is given as string in C#? I don't want a giant if/else tree
You can use reflection:
var obj = new { A = 5 } as object; // your object
var five = obj.GetType().GetProperty("A").GetValue(obj);
Also, you can use dynamic:
var fiveDynamic = (obj as dynamic).A;
You can do this, of course
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
but you'll get much more new problems than you'll solve. The main is: you don't know the type of the value. It doesn't matter in Javascript, but you cannot say the same about C#. If you are sure to make one more step to make your code a mess, do this
var type = src.GetType().GetProperty(propName).GetType();
var value = src.GetType().GetProperty(propName).GetValue(src, null);
Convert.ChangeType(value, type);