0

I would like to know if it possible to for example use variable as property or method or command. What I mean for example that I would save ".length" as a string, lets call it len. And then use it on word as a property.

For example:

String len = ".length"
string C = "Cat"
int L_Cat = C.len

Now this does not work but C.Length would work. So is there a way to get the .Length out of the string status and evaluate it as a property?

Nino
  • 6,931
  • 2
  • 27
  • 42
  • I'm not sure, but you can always use extension properties. – ThePerplexedOne May 18 '17 at 10:45
  • 2
    You can use reflection for finding and calling by name that method/property if it exists – Samvel Petrosov May 18 '17 at 10:45
  • 5
    Can you name a case in which you would want to use something like this? It flies in the face of type safety and goes against the general structure of C#. The better way to do it would be via interface implementation or class inheritance. Without a proper use case (that warrants not using interfaces or inheritance), I think your question is a case of the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem); where you are asking how to implement a specific solution, rather than asking for help about the actual problem you're trying to solve. – Flater May 18 '17 at 10:46

2 Answers2

2

you can do it like this:

String len = "Length";
string C = "Cat";

var prop = C.GetType().GetProperty(len);
int i = (int)prop.GetValue(C);
Nino
  • 6,931
  • 2
  • 27
  • 42
0

Yes, you can use Reflection to do this.

You could write code similar to the following:

string len = "Length";
string C = "Cat";
int L_Cat = (int)C.GetType()
             .GetProperties()
             .Single(x => x.Name == len)
             .GetValue(C);
toadflakz
  • 7,764
  • 1
  • 27
  • 40