static Class in C-Sharp / C#

It is also possible to apply the static keyword directly on the class level.
When a class has been defined as static, it is not creatable using the new keyword, and it can contain only members or data fields marked with the static keyword. If this is not the case, you receive compiler errors.
At first glance, this might seem like a fairly odd feature, given that a class that cannot be created does not appear all that helpful. However, if you create a class that contains nothing but static members and/or constant data, the class has no need to be allocated in the first place! To illustrate, create a new Console Application named SimpleUtilityClass. Next, define the following class:



Code Snippet
  1. / Static classes can only
  2. // contain static members!
  3. static class TimeUtilClass
  4. {
  5.   public static void PrintTime()
  6.   { Console.WriteLine(DateTime.Now.ToShortTimeString()); }
  7.  
  8.   public static void PrintDate()
  9.   { Console.WriteLine(DateTime.Today.ToShortDateString()); }
  10. }
  11. Given that this class has been defined with the static keyword, you cannot create an instance of
  12. TimeUtilClass using the new keyword.  Rather, all functionality is exposed from the class level:
  13. static void Main(string[] args)
  14. {
  15.   Console.WriteLine("***** Fun with Static Classes *****\n");
  16.  
  17.   // This is just fine.
  18.   TimeUtilClass.PrintDate();
  19.   TimeUtilClass.PrintTime();
  20.   // Compiler error! Can't create static classes!
  21.   TimeUtilClass u = new TimeUtilClass ();
  22.   
  23.   Console.ReadLine();
  24. }


Post a Comment