Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically reference incremented properties in C#?

I have properties called reel1, reel2, reel3, and reel4. How can I dynamically reference these properties by just passing an integer (1-4) to my method?

Specifically, I am looking for how to get an object reference without knowing the name of the object.

In Javascript, I would do:

temp = eval("reel" + tempInt);

and temp would be equal to reel1, the object.

Can't seem to figure this simple concept out in C#.

like image 542
Jeff Blankenburg Avatar asked Apr 12 '10 15:04

Jeff Blankenburg


1 Answers

This is something that's typically avoided in C#. There are often other, better alternatives.

That being said, you can use Reflection to get the value of a property like this:

object temp = this.GetType().GetProperty("reel" + tempInt.ToString()).GetValue(this, null);

A better alternative, however, might be to use an Indexed Property on your class, which would allow you to do this[tempInt].

like image 124
Reed Copsey Avatar answered Sep 22 '22 03:09

Reed Copsey