-3

Suppose I have a class like

class Test {
  public Test() {
    Name = "Hello";
  }

  public string Name { get; set; }
}

I want a function which, when given an object and a string, returns the value of the property of the object whose name is the string. For example,

Test myTest = new Test();
string myName = f(myTest, "Name"); // myName == "Hello"

Is this possible? Does there exist such a function?

79037662
  • 117
  • 5
  • 1
    You can do that using reflection. But I wouldn't recommend it unless you know exactly what you are doing _and why_. Looks like a [x-y-Question](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Fildor Apr 08 '21 at 13:28

1 Answers1

1

You are after reflection.

Test myTest = new Test();

string myName = (string)myTest.GetType().GetProperty("Name")?.GetValue(myTest); // myName == "Hello"
Cetin Basoz
  • 22,495
  • 3
  • 31
  • 39
  • OP: Mind that this code assumes `Test` _must_ have that property "Name". It will fail (i.e. throw a runtime exception) otherwise. – Fildor Apr 08 '21 at 13:31
  • @Fildor, you can check it. Anyway editing for your taste. – Cetin Basoz Apr 08 '21 at 13:31
  • It's fine. I only wanted to give OP a heads up. If he puts this into a function to use it on any other object, he might have to deal with exceptions. Using it like you did in the answer will be safe, tough (because restricted to the Test class, only). – Fildor Apr 08 '21 at 13:33
  • 1
    @Fildor, OK. In a function though I would expect it would use GetProperties and probably use a KV collection. – Cetin Basoz Apr 08 '21 at 13:35