C# Tutorial - Dissecting Our Fifth Application – staticIn our application, we declared the GetNumber method to be static. But what does this mean? Anything that is given the static modifier belongs to the class rather than an instance of the class (object). In simple terms it means that we can use the method GetNumber without creating an instance of the Program class. The static modifier can be used with classes, attributes, methods, properties and constructors. However static cannot be used with destructors, or types other than classes. Static MembersAny static member can only be called from within a static method, or through the type name. In our application, the method GetNumber was called from the static method Main. If we wanted to call this method from another class we would simply achieve this by prefixing the GetNumber method with the class name Program. Program.GetNumber(); Any method that is static can only use other static methods, static attributes and static properties of the same class. When you try to do otherwise, a compiler error will happen. This can be shown in a simple example: class aClass
{
private int a;
private static int b;
public static void AddNumbers()
{
// compilation error occurs here as "a" has no memory
a = a + 10;
// "b" is static, so this is fine
b = b + 10;
}
}
When the method AddNumbers is called, the attribute "a" has no memory associated with it, so when we try to increment it, the compiler throws and error. If we create an instance of aClass, the attribute "a" now has some memory associated with it, but we cannot call the method AddNumbers as part of the instance of aClass as this will result in a compiler error. Static ClassesA static class can only have static members and you cannot create an instance of a static class. This also means that you cannot inherit from them. So what can a static class do for you? Well they can be ideal for utility classes, one that contains methods that are used widely throughout an application.
|