Thursday, 28 November 2013

Static Classes and Static Class Members in C#

Main features of a static class:

  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed and therefore cannot be inherited
  • Cannot contain Instance Constructors. Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.
  • It can contain a static constructor.

Main features of a static member:

  • A non-static class can contain static methods, fields, properties, or events.
  • The static member is callable on a class even when no instance of the class has been created.
  • The static member is always accessed by the class name, not the instance name.
  • Only one copy of a static member exists, regardless of how many instances of the class are created.
  • Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
  • Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
  • Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
  • Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.
  • C# does not support static local variables (variables that are declared in method scope).
  • Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.
  • To access a static class member, use the name of the class instead of a variable name to specify the location of the member.
  • If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
  • A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
Read more>>

No comments:

Post a Comment