0

So I am trying to access a property of an object based on variable name.

is this possible in C# like Javascript?

class Demo {
public string A {get; set;}
public string B {get; set;}
.....
}

List<Demo> items; 

public void getSomething(string prop){
foreach (item in items){
 Console.writeline(item.A + item[prop]);
}
}

getSomething("B");
smj
  • 416
  • 1
  • 4
  • 10
  • 1
    You can read about [reflection](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection). As alternative you can add an [indexer](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/) to `Demo` class – Aleks Andreev Apr 05 '19 at 12:15
  • You can, but in a less easy way and it is called [Reflection](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection). – Peter B Apr 05 '19 at 12:15
  • You can't. It's strongly typed. If you want accessing properties when not knowing the type of the object, declare a base class with that properties and make derived classes that inherit from it. – trollingchar Apr 05 '19 at 12:19

0 Answers0