I was wondering what are the general benefits (or drawbacks) of using a non-static class with a static method versus a static class with the same static method, other than the fact that I cannot use static methods from a non-static class as extension methods.
For example:
class NonStaticClass
{
public static string GetData()
{
return "This was invoked from a non-static class.";
}
}
Versus this:
static class StaticClass
{
public static string GetData()
{
return "This was invoked from a static class.";
}
}
What are the performance/memory implications of using one method over another?
NOTE: Suppose that I do not need to instantiate the class. My use-case scenario is limited to something like this:
Console.WriteLine(NonStaticClass.GetData());
Console.WriteLine(StaticClass.GetData());
The main benefit is that if you make the class static, the compiler will make sure that your class will only have static members.
So anyone reading the code, will instantly see the class can't be instantiated, and there is no interaction to be considered with any instances of the class. Because there can't be any.
At the clr level, there is no notion of static
. A static class is both abstract
and sealed
, which effectively prevents inheritance and instantiation.
As for performance, I don't see any possiblities for compiler or runtime to optimize one over the other.
In this example, I would focus on expressing your intent as clear as possible to the readers. You can always optimize later.
There are some peculiarity/limitation:
So if you suppose such a behavior for you class (e.g. helper/util or extension methods container), if you want to limit it's usage - make it static
.
There are no benefits or drawbacks. It's just architectual decision.
Use static only classes in cases of providing a function set or function libriary. As you can not instantiate it, but you can use it like.
MyMathLibrary.Plot(...)
This types are usually imply state less behavior. I repeat, usually.
Use simple classes with static members when you have "normal" type but need somehow a stateless method, like for example:
public class MyType
{
.... //some members
public static MyType ReadFromXml(XmlReader reader) {}
public static void SaveToXml(MyType mt) {}
}
There is no a silver bullet, it's just a matter of architect choice.
Performance implications: basically none.
You can create an instance of NonStaticClass
, but since it has no non-static overriden methods it's pretty much as useful as saying object obj = new object()
, which is to say it's useful for maybe locking and that's about it. Making the class static prevent someone from new-ing it, but it's not like that does any real harm.
It's more of a self documenting way of saying there's no reason to create an instance of the class.