What is the difference between a static class and a normal class?
- static classes cannot be
instantiated
orinherited
. - static classes are marked as
sealed
andabstract
by compiler in the output MSIL. - all members of static classes must be static as well.
- only static classes can host
extension methods
. - static classes cannot be used as generic type arguments.
Static classes contain static objects that can't be instantiated multiple times. Usually what I use static classes for are to house static methods that provide calculations, general processing patterns, string output formats, etc. Static classes are light weight and don't need instantiation.
For instance System.IO.File
is a static class with static a method Exists()
. You don't create a File object to call it. You invoke it like this
System.IO.File.Exists(filePath)
Rather than doing this
System.IO.File myFile = new System.IO.File(filePath);
if(myFile.Exists())
{ /* do work */ }
If you require several objects in software, then you use dynamic classes. For instance if you have an inventory system you may have several Product
objects and in that case you would use a dynamic class such as this
public class Product
{
public int ProductID { get; private set; }
public string ProductName { get; private set; }
public int Qty { get; set; }
public Product( int productID, string productName, int total )
{
this.ProductID = productID;
this.ProductName = productName;
this.Qty = total;
}
}
You can create instances of "normal" classes via the class constructor.
var normal = new Normal();
You cannot create instances of static classes. They can only have static methods.
Also worth noting is that you must declare extension methods in static classes.
From the MSDN documentation on static classes:
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.