Wednesday, December 26, 2007

Static Members (2) Things to note

Static members

  • A static member belongs to the class rather than to the objects of the class.
  • Static members are also known as class members and non-static members are known as instance members.
  • Indexers in C# can't declared as static.
  • All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.
  • A derived class can inherit a static member.
  • But a static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.

Static constructor

  • A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only.
  • It is called automatically before the first instance is created or any static members are referenced.
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

Static Constructors (C# Programming Guide)

C# - Static Members

blog comments powered by Disqus