Tuesday, November 18, 2008

Uses of the Static Keyword in C#.NET (Static Methods)

Let us consider a class named Teenager that defines a static method named Complain(), which returns a random string, obtained in part by calling a private helper function named GetRandomNumber():

class Teenager
{
private static Random r = new Random();

private static int GetRandomNumber(short upperLimit)
{
return r.Next(upperLimit);
}

public static string Complain()
{
string[] messages = new string[5]{ "Do I have to?",
"He started it!",
"I'm too tired...",
"I hate school!",
"You are sooo wrong."
};
return messages[GetRandomNumber(5)];
}
}

Notice that the System.Random member variable and the GetRandomNumber() helper function method have also been declared as static members of the Teenager class.

Like any static member, to call Complain(), prefix the name of the defining class:

// Call the static Complain method of the Teenager class.   
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
Console.WriteLine("-> {0}", Teenager.Complain());
}

And like any nonstatic method, if the Complain() method was not marked static, you would need to create an instance of the Teenager class before you could hear about the gripe of the day:

// Nonstatic data must be invoked at the object level.   
Teenager joe = new Teenager();
joe.Complain();

No comments: