0

In php you can create variables with variable names using ${'variable'.$count}

but at the moment I need this in C#, is there a C# equivalent for this?

EDIT:

Basically what im trying to do is create a timer every time the space bar is pressed, the first time the name is timer1 second time timer2..

Wim
  • 85
  • 1
  • 14
  • 1
    After your Edit: I would still go for a Dicitonary because that's the way to keep track of values by keys. (Dictionary also ensures there are no duplicate keys). However I Would change the type for the value from object to Timer – middelpat May 28 '14 at 12:20

2 Answers2

2

You could store the values in a Dictionary in C#. That way you could retrieve a value according to a specific key.

IDictionary<string, object> variables = new Dictionary<string, object>();

Add a variable:

variables.Add("varname", 11);

Then to retrieve te variables you can use:

var myVar = variables.SingleOrDefault(x => x.Key == "varname");

Note to include using System.Linq; to use .SingleOrDefault()

Because the object type is used as a value, all kinds of variables can be stored; (int, string, custom class instances). but note that you'll have to cast the variable back to your type when using it

EDIT: If you only use Timers, use this dictionary declaration:

IDictionary<string, Timer> variables = new Dicitonary<string, Timer>();
middelpat
  • 2,555
  • 1
  • 20
  • 29
  • Using Dictionary is a good way! +1 – Rahul Tripathi May 28 '14 at 12:02
  • Thank you for your help. Can I use a variable instead of 11? – Wim May 28 '14 at 12:41
  • 2
    @Wim 11 is an int variable. You can use any variable you want. Also a Timer as your edit reveils. But if the collection will only contain timers, i suggest changing the object Type of the dictionary to Timer. In that way you won't need to cast the value back after retrieving it – middelpat May 28 '14 at 12:48
1

Then create your own Timer type, where you encapsulate the logic of updating the name. No need for variable variables.

class MyTimer
{
 // ...

 public void Increment()
 {
   this.name = "name" + (count++).ToString();
 }

 private string name;
 private int cout;
}
quantdev
  • 23,517
  • 5
  • 55
  • 88