Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# comparing private static and public static method

Tags:

c#

In C#, what is the difference between methods that are markedpublic staticand methods marked asprivate static?

How are they allocated and accessed?

like image 488
Vikram Avatar asked Dec 10 '10 04:12

Vikram


2 Answers

A private static method can only be accessed within the class that it's defined in. A public static method can be accessed outside of the class.

public class MyClass
{ 
    private static void MyPrivateMethod()
    {
        // do stuff
    }

    public static void MyPublicMethod()
    {
        // do stuff
    }
}

public class SomeOtherClass
{
    static void main(string[] args)
    {
         MyClass.MyPrivateMethod(); // invalid - this method is not visible

         MyClass.MyPublicMethod(); // valid - this method is public, thus visible
    }
}

As far as memory allocation goes, see here:

Where are methods stored in memory?

like image 51
Tyler Treat Avatar answered Nov 14 '22 23:11

Tyler Treat


Private static methods can only be accessed by other methods in that class. Public static methods are pretty much global in access.

like image 21
Jon Abaca Avatar answered Nov 14 '22 22:11

Jon Abaca