Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a static function:

static string GenRan()
{
    List<string> s = new List<string> {"a", "b"};
    int r = Rand();
    string a = null;

    if (r == 1)
    {
        a += s[0];
        s.RemoveAt(0);
    }
    if (r == 2)
    {
        a += s[1];
        s.RemoveAt(1);
    }
    return a;
}

But everytime I call the function of course, the list is reset, so I would like to access the list from outside the static function.

Is there a way?

I tried:

static void Main(string[] args)
{
    List<string> s = new List<string> {"a", "b"};
    string out = GenRan(s);
}

static string GenRan(List<string> dict)
{

    int r = Rand();
    string a = null;

    if (r == 1)
    {
        a += s[0];
        s.RemoveAt(0);
    }
    if (r == 2)
    {
        a += s[1];
        s.RemoveAt(1);
    }
    return a;
}

But then I get an Index is out of range error (not sure why).

Can anyone help?

share|improve this question

2 Answers

up vote 7 down vote accepted

You need to add it to the class as static field variable:

private static List<string> s = new List<string> { "a", "b" };

static string GenRan()
{
    int r = Rand();
    string a = null;

    if (r == 1)
    {
        a += s[0];
        s.RemoveAt(0);
    }
    if (r == 2)
    {
        a += s[1];
        s.RemoveAt(1);
    }
    return a;
}
share|improve this answer

But everytime I call the function of course, the list is reset, so I would like to access the list from outside the static function.

It's not really clear what you mean, but if you mean you want the list to be persistent between calls, you need to declare it as a static variable, outside the method:

private static readonly List<string> s = new List<string> {"a", "b"};

Now you can access the list from any method, and it's basically part of the state of the class. However, this approach comes with lots of caveats:

  • List<T> is not thread-safe, and typically static methods should be thread-safe. If you're just new to C# and not using multiple threads, you can probably ignore that for now.
  • You should really rename the variable - s gives no indication of what the list is meant to represent.
  • In general, global mutable state is a bad idea. It makes it hard to test your code, and to reason about it. Again, if you're new to C# and just experimenting, you may not need to worry about this, but as you move on you should try to put more mutable states in objects rather than just static variables.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.