1

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

Zer0
  • 1,580
  • 10
  • 28
  • 4
    You can use reflection - but this may well not be the best approach. You may be better off just using a dictionary. Without knowing anything about the bigger context, it's hard to say. – Jon Skeet Aug 28 '20 at 07:35
  • I'm trying to edit an item in the list where I receive the edited property name as a string – Zer0 Aug 28 '20 at 07:36
  • Yes it does, thank you! I don't know how I didn't stumble upon this when googling – Zer0 Aug 28 '20 at 07:40
  • 1
    I would not recommend reflection, you can simply create a dictionary and obtain the value using the key associated to it. – t00n Aug 28 '20 at 07:42
  • This is an XY problem, C# is a typed language and nothing like JavaScript. I suggest learning how to use it as a typed language and you might have a much easier time.. Or if you want, add more information about the problem you are actually trying to solve, you might find people can suggest better solutions – TheGeneral Aug 28 '20 at 07:59

2 Answers2

5

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;
Dilshod K
  • 2,924
  • 1
  • 13
  • 46
1

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);
Roman Ryzhiy
  • 1,540
  • 8
  • 5
  • "_you don't know the type of the value_" Why assume that? The compiler doesn't know the type, but the developer might. Also `Convert.ChangeType` achieves nothing here; your getting the type of the object using reflection, then converting the object to the type that it already is. You are probably looking for a cast, but in that case the developer _does_ claim to know the type. – Johnathan Barclay Aug 28 '20 at 08:31