C# 2.0 Features - Part 2.9 Static Classes

Apr
24
2011
In Categories: .NET | CLR
Tags | |

You can see part 1 here, part 2.1 here, part 2.2 here, part 2.3 here, part 2.4 here, part 2.5 here, part 2.6 here, part 2.7 here and part 2.8 here.

We can now mark the class with static modifier to declare that this class has no state. We need this type of classes for utility classes like System.Math. You can also have static constructor. Let's have a look

    1 public static class Utility

    2 {

    3     private static readonly string Path;

    4 

    5     static Utility()

    6     {

    7         Path = "The Path";

    8     }

    9 

   10     static string GetBasePage()

   11      {

   12         return Path + "/BasePage";

   13      }

   14 }

As you can see here this is a normal class that has constructor except that all the members is static. You should take care when to use static classes as these kind of classes is loaded by the CLR once the namespace containing this class is loading.

Comments are closed