Accessing from a static method

My brain is not working today. I need help accessing some members from a static method. Here is sample code, how can I change 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 } } 
+6
c # static-methods
source share
4 answers

testInt declared as an instance field. The static method cannot access an instance field without reference to an instance of the defining class. So declare testInt as static or modify TestMethod to accept an instance of TestPage . So

 protected static int testInt { get; set; } 

good like

 public static void TestMethod(TestPage testPage) { Console.WriteLine(testPage.testInt); } 

Which one is correct depends a lot on what you are trying to model. If testInt represents the state of the TestPage instance, then use the latter. If testInt is something like TestPage , then use it.

+10
source share

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

  • Make the testInt property static.
  • Modify TestMethod so that it TestPage instance of TestPage as an argument.
+6
source share
 protected static int testInt { get; set; } 

But be careful with threading issues.

+4
source share

Remember that static means that a member or method belongs to a class, not an instance of a class. Therefore, if you are in a static method and want to access a non-stationary member, then you must have an instance of the class for which you can access these members (if the members should not belong to any particular instance of the class, in which case you can just make them static). A.

+4
source share

All Articles