2

How to create dynamic incrementing variable using "for" loop in C#? like this: track_1, track_2, track_3, track_4. so on.

2
  • 6
    Mind posting some code what of you've already done/tried? Commented Sep 12, 2011 at 10:51
  • 3
    Why would you want to do that? Commented Sep 12, 2011 at 10:53

7 Answers 7

8

You can't create dynamically-named variables. All you can do - it to create some collection or array, and operate with it. I think the best class for you is generic List<>:

List<String> listWithDynamic = new List<String>();
for (int i = 1; i < limit; i +=1)
{
    listWithDynamic.Add(string.Format("track_{0}", i));
    ...
}
Sign up to request clarification or add additional context in comments.

7 Comments

if it's in a for loop he might know the count up front making an array possible
@Rune FS according the OP's and so on I thought that he don't know the .Count
yes it's possible to change the number of iterations of a for loop inside the loop but it's uncommon if he knows the number of iterations. I would assume he knows the number of objects he needs. However all that is of course only assumptions and if any of the are wrong he''l have to use List<T> or something similar
You can, even with just a local variable.
@Jonathan Dickinson Really? Create variable with dynamic name? Can you show some code?
|
2

Assuming you want strings:

for (int i = 1; i < limit; i +=1)
{
    string track = string.Format("track_{0}", i);
    ...
}

But when you already have variables called track_1, track_2, track_3, track_4 you will need an array or List:

var tracks = new TrackType[] { track_1, track_2, track_3, track_4 } ;

for (int i = 0; i < tracks.length; i++)
{
    var track = tracks[i];  // tracks[0] == track_1
    ...
}

2 Comments

I think he wants to generate the variable name dynamically, like it is possible in some dynamically typed languages.
+1 for figuring out that he might not be talking about strings.
1

Obvious Solution

for (var i = 0; i < 10; i++)
{
    var track = string.Format("track_{0}", i);

}

Linq-Based Solution

foreach (var track in Enumerable.Range(0, 100).Select(x => string.Format("track_{0}", x)))
{

}

Operator-Based Solution This is somewhat hacky, but fun none-the-less.

for (var i = new Frob(0, "track_{0}"); i < 100; i++)
{
    Console.WriteLine(i.ValueDescription);
}

struct Frob
{
    public int Value { get; private set; }
    public string ValueDescription { get; private set; }
    private string _format;

    public Frob(int value, string format)
        : this()
    {
        Value = value;
        ValueDescription = string.Format(format, value);
        _format = format;
    }

    public static Frob operator ++(Frob value)
    {
        return new Frob(value.Value + 1, value._format);
    }

    public static Frob operator --(Frob value)
    {
        return new Frob(value.Value - 1, value._format);
    }

    public static implicit operator int(Frob value)
    {
        return value.Value;
    }

    public static implicit operator string(Frob value)
    {
        return value.ValueDescription;
    }

    public override bool Equals(object obj)
    {
        if (obj is Frob)
        {
            return ((Frob)obj).Value == Value;
        }
        else if (obj is string)
        {
            return ((string)obj) == ValueDescription;
        }
        else if (obj is int)
        {
            return ((int)obj) == Value;
        }
        else
        {
            return base.Equals(obj);
        }
    }

    public override int GetHashCode()
    {
        return Value;
    }

    public override string ToString()
    {
        return ValueDescription;
    }
}

Comments

0

don't know if I get your question, but I will try:

for(var i = 1; i < yourExclusiveUpperbound; i++)
{
   var track = String.Format("$track_{0}", i);
   // use track
}

or with some LINQ-Magic:

foreach(var track in Enumerate.Range(1, count)
                              .Select(i => String.Format("$track_{0}", i)))
{
   // use track
}

Comments

0

Do as follow:

for (int i = 0; i < lenght; i ++)
{
    any work do in loop
}

Comments

0

No, we can't create dynamically named variables in a loop. But, there are other elegant ways to address the problem instead of creating dynamically named variables.

One could be, create an array or list before the loop and store values in array / list items in the loop. You can access the array / list later anywhere in your code. If you know which variable you want to use (track_1, track_2, ...), you can simply access it from the array / list (tracks[1], tracks[2], ...).

List<String> tracks = new List<String>();
for (int i = 1; i < limit; i++)
{
    Track track = new Track();
    tracks.Add(track);
    ...
}

Comments

0
  for (int i=5;i<30;(i%2==0)?i=i+4:i=i+2) {
     cout<<i;
     cout<<endl;
   }

Using ternary operator can help.

1 Comment

cout doesn't seem like C# to me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.