5

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

How are they allocated and accessed?

Rob Kielty
  • 7,740
  • 7
  • 37
  • 50
Vikram
  • 465
  • 2
  • 8
  • 13
  • -1 for not looking at a C# tutorial first, or searching google. There are hundres of examples of how to use different access levels (public, protected, internal, private). – John Alexiou Dec 10 '10 at 04:58

3 Answers3

9

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?

Community
  • 1
  • 1
Tyler Treat
  • 14,350
  • 13
  • 77
  • 113
1

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

Jon Abaca
  • 801
  • 1
  • 8
  • 14
0

Static methods are applied at a class level, ie, an object is not required to access them. The only difference between public and private methods is accessibility.

  • Private methods are visible only to other methods within that class.
  • Public methods are visible to any other class.

    Static methods can be accessed by both static and non-static methods.
  • AK.
    • 733
    • 7
    • 13