Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Nbsp;   Static Classes

There are certain classes that are never intended to be instantiated, such as Console, Math, Environment, and ThreadPool. These classes have only static members and, in fact, the classes exist simply as a way to group a set of related members together. For example, the Math class defines a bunch of methods that do math-related operations. C# allows you to define non-instantiable classes by using the C# static keyword. This keyword can be applied only to

classes, not structures (value types) because the CLR always allows value types to be instantiated and there is no way to stop or prevent this.

The compiler enforces many restrictions on a static class:

 

■ The class must be derived directly from System.Object because deriving from any other base class makes no sense because inheritance applies only to objects, and you cannot create an instance of a static class.

■ The class must not implement any interfaces because interface methods are callable only when using an instance of a class.

■ The class must define only static members (fields, methods, properties, and events). Any

instance members cause the compiler to generate an error.

 

■ The class cannot be used as a field, method parameter, or local variable because all of these would indicate a variable that refers to an instance, and this is not allowed. If the compiler detects any of these uses, the compiler issues an error.

Here is an example of a static class that defines some static members; this code compiles (with a warning) but the class doesn’t do anything interesting.

 

using System;

 

public static class AStaticClass {

public static void AStaticMethod() { }

 

public static String AStaticProperty { get { return s_AStaticField; }

set { s_AStaticField = value; }

}

 

private static String s_AStaticField;

 

public static event EventHandler AStaticEvent;

}

 

If you compile the code above into a library (DLL) assembly and look at the result by using ILDasm.exe, you’ll see what is shown in Figure 6-2. As you can see in Figure 6-2, defining a class by using the static keyword causes the C# compiler to make the class both abstract and sealed. Furthermore, the compiler will not emit an instance constructor method into the type. Notice that there is no instance constructor (.ctor) method shown in Figure 6-2.


FIGURE 6-2ILDasm.exe showing the class as abstract sealed in metadata.

 


Date: 2016-03-03; view: 704


<== previous page | next page ==>
Nbsp;   Member Accessibility | Nbsp;   Partial Classes, Structures, and Interfaces
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)