#282 – Creating Private Static Methods
March 26, 2011 2 Comments
Like instance methods, static methods can be public or private. A private static method is a method that works with the class’ static data, but is not visible from outside the class.
Below is an example of a private static method. Note that it’s making use of some public static data. It could also work with private static data.
// Static property -- one value for all dogs public static string Creed { get; set; } // Public static method, to recite our creed public static void RepeatYourCreed(int numRepeats) { string creed = FormatTheCreed(); for (int i = 0; i < numRepeats; i++) Console.WriteLine(creed); } // Private method to format our Dog creed private static string FormatTheCreed() { return string.Format("As dogs, we believe: {0}", Dog.Creed); }
We can call the public static method that makes use of this private method:
// Set static property Dog.Creed = "We serve man"; // Call static method Dog.RepeatYourCreed(3);
Could you please also explain how to call the Private Static Methods?
Niraj, to call the static method, you prefix the method name with the class name. See https://csharp.2000things.com/2011/03/25/281-declaring-and-using-static-methods-in-a-class/
When a static method is private, you can only call it from within the class in which it is defined.