I have two classes Class A and ClassB:
static class ClassA { static string SomeMethod() { return "I am a Static Method"; } } class ClassB { static string SomeMethod() { return "I am a Static Method"; } }
I want to know what is the difference between ClassA.SomeMethod();
and ClassB.SomeMethod();
When they both can be accessed without creating an instance of the class, why do we need to create a static class instead of just using a non static class and declaring the methods as static?
Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding. A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding.
Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.
Difference between static and non-static classStatic class is defined using static keyword. Non-Static class is not defined by using static keyword. In static class, you are not allowed to create objects. In non-static class, you are allowed to create objects using new keyword.
The only difference is that static methods in a nonstatic class cannot be extension methods.
In other words, this is invalid:
class Test { static void getCount(this ICollection<int> collection) { return collection.Count; } }
whereas this is valid:
static class Test { static void getCount(this ICollection<int> collection) { return collection.Count; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With