Static Classes
Reference: CLR via C# book
1. There are certain classes that are never
intended to be instantiated, such as Console, Math, Environment and
Thread Pool. C# allows you to define non- insatiable classes by using the C# static
keyword
2. These classes have only static members
and, in fact, the classes exist simply as a way to group a set of related
members together
3. 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
4. The class must be derived directly from System.
Object because deriving from any other base class makes no sense since
inheritance applies only to objects, and you cannot create an instance of a static
class
5. The class must not implement any
interfaces since interface methods are callable only when using an instance of
a class.
6. The class must define only static members
(fields, methods, properties, and events).
7. Any instance members cause the compiler
to generate an error.
8. 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.
9. 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 . As you can see in Figure, defining aclass 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. Figure is static (sealed and
abstract), the compilerwill not emit a default constructor at all into the
class definition.
No comments:
Post a Comment