#282 – Creating Private Static Methods
March 26, 2011 Leave a comment
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);
