Reputation: 10153
My brain is not working this morning. I need some help accessing some members from a static method. Here is a sample code, how can I modify this so that TestMethod() has access to testInt
public class TestPage
{
protected int testInt { get; set; }
protected void BuildSomething
{
// Can access here
}
[ScriptMethod, WebMethod]
public static void TestMethod()
{
// I am accessing this method from a PageMethod call on the clientside
// No access here
}
}
Upvotes: 6
Views: 2360
Reputation: 241779
testInt
is declared as an instance field. It is impossible for a static
method to access an instance field without having a reference to an instance of the defining class. Thus, either declare testInt
as static, or change TestMethod
to accept an instance of TestPage
. So
protected static int testInt { get; set; }
is okay as is
public static void TestMethod(TestPage testPage) {
Console.WriteLine(testPage.testInt);
}
Which of these is right depends very much on what you're trying to model. If testInt
represents state of an instance of TestPage
then use the latter. If testInt
is something about the type TestPage
then use the former.
Upvotes: 10
Reputation: 83310
Remember that static
means that a member or method belongs to the class, instead of an instance of the class. So if you are inside a static method, and you want to access a non-static member, then you must have an instance of the class on which to access those members (unless the members don't need to belong to any one particular instance of the class, in which case you can just make them static).
Upvotes: 4
Reputation: 269618
Two options, depending on what exactly you're trying to do:
testInt
property static.TestMethod
so that it takes an instance of TestPage
as an argument.Upvotes: 6
Reputation: 16065
protected static int testInt { get; set; }
But be careful with threading issues.
Upvotes: 4