frank3579
frank3579

Reputation: 65

Object inside a class cannot be seen inside a method's for loop

My sample code:

public partial class Service1 : ServiceBase
{
    object a = new object ();

    static void methodA()
    {
        string[] tests = {"test1","test2","test3"}
        foreach(string test in tests)
        {
            a.SetValue(""); //object a cannot be seen
        }
    }
}

Object cannot be seen. How can I use the object inside a for loop?

Upvotes: 0

Views: 90

Answers (3)

vossad01
vossad01

Reputation: 11958

The object is not static but the method is. Change the declaration to:

static Object a = new Object ();

and it will be accessible from within your loop.

Your other option is to make the method not static. Which you choose really depends on which behavior you want.

Upvotes: 4

jr pineda
jr pineda

Reputation: 186

Your method is static, that's why you can't access the object. Try making your object static as well.

Upvotes: 1

horgh
horgh

Reputation: 18563

Your method is static. You cannot access non-static fields from static methods. Consider if your method (or variable) is supposed to be static and

  1. Declare your variable with static keyword
  2. Remove static keyword from the method declaration

Here is the static (C# Reference)

Upvotes: 6

Related Questions