I was asked the above question in an interview. Could you please explain the differences? ( performance - memory - usage - when to use which ? )
Thank you,
Erkan
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.
A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.
A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.
A static class can only contain static members. A static method ensures that, even if you were to create multiple classB objects, they would only utilize a single, shared SomeMethod function. Technically, there's no difference, except that ClassA's SomeMethod must be static.
Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error.
A non-static class with static members usually indicates that the class is designed to be instantiated at some point. Static methods of these classes usually do one of two things:
Also, as mentioned already, extension methods can only be declared on a static class.
I assume you were asked for the differences?
A static method on a static class can be used to define an extension method. A static method on a non-static class cannot.
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