A static method is a method that exists in a class as a whole rather than in a specific instance of the class. As with other static members, the key benefit to static methods is that they reside apart from a particular instance of a class without polluting the application's global space and without going against the object-oriented grain by not being associated with a class. An example of this is a database API I wrote in C#. Within my class hierarchy, I had a class called SQLServerDb. Along with the basic NURD (new, update, read, and delete) capabilities, the class also exposed a method to repair the database. In the class's Repair method, I had no need to open the database itself. In fact, the ODBC function I used (SQLConfigDataSource) mandated that the database be closed for the operation. However, the SQLServerDb constructor opened a database specified in a database name passed to it. Therefore, a static method was perfect. It allowed me to place a method in the SQLServerDb class where it belonged and yet not go through my class's constructor. Obviously, on the client side, the benefit was that the client didn't have to instantiate the SQLServerDb class either. In the next example, you can see a static method (RepairDatabase) being called from within the Main method. Notice that we don't create an instance of SQLServerDB to do this: -
using System;
class SQLServerDb
{
// Bunch of other nonsalient members.
public static void RepairDatabase()
{
Console.WriteLine("repairing database...");
}
}
class StaticMethod1App
{
public static void Main()
{
SQLServerDb.RepairDatabase();
}
}
Defining a method as static involves using the static keyword. The user then employs the Class.Method syntax to call the method. Note that this syntax is necessary even if the user has a reference to an instance of the class. To illustrate this point, the following code would fail to compile: -
// This code will fail to compile.
using System;
class SQLServerDb
{
// Bunch of other nonsalient members.
public static void RepairDatabase()
{
Console.WriteLine("repairing database...");
}
}
class StaticMethod2App
{
public static void Main()
{
SQLServerDb db = new SQLServerDb();
db.RepairDatabase();
}
}