ASP.NET 2.0 Resources

Powered by Blogger

C# 2.0 Features: Static Classes

C# 2.0 contains one very nice feature called static classes. Maybe you already encountered situation where creating instance of some class was useless because it contained only static methods. In C# 1.1 you would have to create sealed class with private contructor to disable creation of instances and deriving your class.

public class MyUtilities {
    private MyUtilities() {}
    
    public static string HelloWorld() {
        return "Hello world";
    }
}

In C# you can declare class as static.

public static class MyUtilities
{  
   public static string HelloWorld() {
           return "Hello world";
   }
}

The C# 2.0 compiler will not allow you to add a non-static member to a static class, and will not allow you to create instances of the static class as if it were an abstract class. In addition, you cannot derive from a static class. It's as if the compiler adds both abstract and sealed to the static class definition. Note that you can define static classes but not static structures, and you can add a static constructor.

0 Comments:

Post a Comment

<< Home

Created dolly