In C# a public member can be called from external locations. Used on members, classes and method declarations, public is not the default accessibility.
Meanwhile, a private method cannot be called from outside its class
. It can be called only from other class
methods—this promotes information hiding.
We show how to define public methods. We then call those methods from outside the class
. Public is an accessibility modifier. It is not the default, which is private.
static
. This means they are attached to the type itself.using System; public class Example { static int _fieldStatic = 1; // Private static field int _fieldInstance = 2; // Private instance field public static void DoStatic() { // Public static method body. Console.WriteLine("DoAll called"); } public static int SelectStatic() { // Public static method body with return value. return _fieldStatic * 2; } public void DoInstance() { // Public instance method body. Console.WriteLine("SelectAll called"); } public int SelectInstance() { // Public instance method body with return value. return _fieldInstance * 2; } } class Program { static void Main() { // First run the public static methods on the type. Example.DoStatic(); Console.WriteLine(Example.SelectStatic()); // Instantiate the type as an instance. // ... Then invoke the public instance methods. Example example = new Example(); example.DoInstance(); Console.WriteLine(example.SelectInstance()); } }DoAll called 2 SelectAll called 4
This program shows how the private modifier (on a method) affects how the method can be invoked. It shows instance methods and a private static
method.
Program
, you can only access the public methods.using System; class Test { private int Compute1() { return 1; // Private instance method that computes something. } public int Compute2() { return this.Compute1() + 1; // Public instance method. } private static int Compute3() { return 3; // Private static method that computes. } public static int Compute4() { return Compute3() + 1; // Public static method. } } class Program { static void Main() { // Create new instance of the Test class. // ... You can only call the Compute2 public instance method. Test test = new Test(); Console.WriteLine(test.Compute2()); // Call the public static method. // ... You cannot access the private static method. Console.WriteLine(Test.Compute4()); } }2 4
We can invoke a private method from inside a public method. Private accessibility only affects how external sources can access the class
.
The C# language automatically considers methods to be both instance methods (not static
) and private methods (not public). The private keyword is implicit on all methods.
Methods are implicitly private and instance. You must specify any deviations from this default state. Any method that needs to be public must declare the public modifier.
We considered public and private things in C#. A private method can be invoked from other class
hierarchies. Accessibility is based on lexical scope.