Reputation: 65
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
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
Reputation: 186
Your method is static, that's why you can't access the object. Try making your object static as well.
Upvotes: 1
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
static
keywordstatic
keyword from the method declarationHere is the static (C# Reference)
Upvotes: 6