Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing class member from static method

I know there are a lot of threads talking about this but so far I haven't found one that helps my situation directly. I have members of the class that I need to access from both static and non-static methods. But if the members are non-static, I can't seem to get to them from the static methods.

public class SomeCoolClass
{
    public string Summary = "I'm telling you";

    public void DoSomeMethod()
    {
        string myInterval = Summary + " this is what happened!";
    }

    public static void DoSomeOtherMethod()
    {
        string myInterval = Summary + " it didn't happen!";
    }
}

public class MyMainClass
{
    SomeCoolClass myCool = new SomeCoolClass();
    myCool.DoSomeMethod();

    SomeCoolClass.DoSomeOtherMethod();
}

How would you suggest I get Summary from either type of method?

like image 666
Jeremy Avatar asked Aug 10 '12 17:08

Jeremy


2 Answers

How would you suggest I get Summary from either type of method?

You'll need to pass myCool to DoSomeOtherMethod - in which case you should make it an instance method to start with.

Fundamentally, if it needs the state of an instance of the type, why would you make it static?

like image 194
Jon Skeet Avatar answered Sep 24 '22 17:09

Jon Skeet


You can't access instance members from a static method. The whole point of static methods is that they're not related to a class instance.

like image 44
Manu Clementz Avatar answered Sep 24 '22 17:09

Manu Clementz