public sealed class NonStaticClass
{
public static void MyFirstMethod()
{
//Code Goes Here
}
public static void MySecondMethod()
{
//Code Goes Here
}
}
Now inherit NonStaticClass to MyClass
class MyClass : NonStaticClass
{
}
You will get compile time error “'StaticClassTest.MyClass': cannot derive from sealed type 'StaticClassTest.NonStaticClass'”
Still StaticClass and NonStaticClass are same, So far all the features provided by StaticClass can be achieved using NonStaticClass. If the behaviour same what is the difference, let’s examine it more
3. Static Class and NonStatic Class are not same because Static class cannot contain instance constructors?
Let’s modify the StaticClassTest and make it like below which is having constructor
public static class StaticClass
{
static StaticClass(string MyName)
{
}
public static void MyFirstMethod()
{
//Code Goes Here
}
public static void MySecondMethod()
{
//Code Goes Here
}
}
You will get compile time error “'StaticClassTest.StaticClass.StaticClass(string)': a static constructor must be parameterless”
Let’s modify the NonStaticClass and make it like below which is having constructor
public sealed class NonStaticClass
{
public NonStaticClass(string MyName)
{
//Code Goes Here
}
public static void MyFirstMethod()
{
//Code Goes Here
}
public static void MySecondMethod()
{
//Code Goes Here
}
}
Compile the application, it will compile without any error.
Call MyFirstMethod of NonStaticClass like below
NonStaticClass.MyFirstMethod();
Put a break point on the constructor of NonStaticClass. You will notice constructor won’t be called only MyFirstMethod will called.
Now create object of NonStaticClass like below