views:

128

answers:

4

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
    }  
}
+4  A: 
protected static int testInt { get; set; }

But be careful with threading issues.

Stan R.
Thank you sir. Worked like a champ.
Mike Fielden
Firstly, I'm assuming this is a website. If that is the case, this approach could cause problems.IF the users can set the value of your int, maybe through a input on the page, then they will be fighting over the same value.i.e. User A sets the value to 7. User B sets the value to 5. User A would now see the value as 5.
Mark Withers
then the question should've asked specifically what is the best way to deal with this situation, not how to access a static property. I did upvote the other answers by Luke and Jason however, because they are the correct answers as well.
Stan R.
+5  A: 

Two options, depending on what exactly you're trying to do:

  • Make your testInt property static.
  • Alter TestMethod so that it takes an instance of TestPage as an argument.
LukeH
+3  A: 

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).

danben
+6  A: 

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.

Jason