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.