Search code examples
c#.nettaglib-sharpcscore

How do i stop the variable from resetting


In my code I have a method with the two parameters. One parameter takes in an int value and the other an array.

e.g

 public void NextSong(int i, TagLib.File[] queue)
 {
    i++;
    SONG_URL = queue[i].Name;
    Stop();
    Play();
 }

My problem here is every time this variable is called like so:

NextSong(0, SongQueue);

It reverts back to the amount placed in the parameter field. How do I stop this?


Solution

  • Two ways:

    public int NextSong(int i, TagLib.File[] queue)
    {
        i++;
        SONG_URL = queue[i].Name;
        Stop();
        Play();
        return i;
    }
    
    int i = 0;
    i= NextSong(i, SongQueue);
    

    Here we are passing a variable of i to the method, during the method we increment that variable and then pass it back via the return. We now have reference to that variable.

    OR

    public void NextSong(TagLib.File[] queue, out int i)
    {
        i++;
        SONG_URL = queue[i].Name;
        Stop();
        Play();
    }
    
    int i = 0;
    NextSong(SongQueue, out i);
    

    This uses the out functionality, which enforces someone to pass a variable that will be returned. It passes the variable by reference (You could also use ref, but since int can't be null, it doesn't change much in this case).