Current .Net Version: 2.0.50727
Home
Articles
C# & .Net Framework Reference
Practice C# Online
XML Web Services
RSS Feeds
Code Snippets
T-SQL Scripts
Videos
Valuable Links
Contact Us
Mike's C#, VS.NET and SQL Blog




ROR XML Info.
What's New in C# 2.0 - Static Classes
Author: Michael G.     Last Updated:9/29/2005 8:03:35 PM
Category(ies): C# 2.0, .Net Framework 2.0
Description: Learn all about the new C# 2.0 Framework feature: Static Classes.
  Add & View Comments About this Article

Tested with Microsoft Visual C# 2005 Beta 1, .Net 2.0.40607.42

Well, while not as exciting as many of the other new features of C# 2.0, static classes give us a faster way of implementing classes who's only purpose is to deliver static members. While you can always just create a class with a private constructor, so that it doesn't get instantiated, and then add all static members, static classes enforce those requirements automatically. Static classes are sealed (they can't be derived from), they can't be instantiated (made an instance object from) and they can't contain a constructor. namespace WhatsNew20StaticClasses { class Program { static void Main(string[] args) { MyStaticClass.PrintMessage("Hello World!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } public static class MyStaticClass { public static void PrintMessage(String Message) { Console.WriteLine(Message); } } }

Comments Click Here to Add your Comment
By Vijay @ 7/13/2005 2:18:56 AM

Why at all have Static "Classes" when classes were made to be a blue print of objects that are to be instantiated logically
By Michael G. @ 7/13/2005 11:13:56 AM

The main reason would be: improved performance. Static access means that the instantiation of an object is unncessary. The .Net framework maintains a single object in memory for static members. A static class is more of a rule: it means that you can't instantiate it as an object and that it can only have static members. I use static members whenever possible and only use instantiated class objects whenever more than copy of the object will be necessary to carry the intended function of the project.
By DaveW @ 3/19/2006 5:32:40 PM

Mike,

Static classes can contain constuctrors. You can't specify their protection, and there can be only. Just like highlander.

Regards,
Dave
 
COPYRIGHT/DISCLAIMER | CONTACT US