Static Method of a Static Class vs. Static Method of a Non-Static Class ( C# )

19,489

Solution 1

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:

  1. Provide a factory method for creating an instance of that type;
  2. Provide helper functionality that does not require an instance of the type;

Also, as mentioned already, extension methods can only be declared on a static class.

Solution 2

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.

Solution 3

In terms of performance and memory usage; precisely nothing. Having a static class means you know there are no instances, but back in 1.1 having a private constructor sufficed. Use a static class if it simply makes no sense to have an instance! (utility classes etc)

Solution 4

When you are providing utility functions and all your methods are static, I recommend you use static methods in a static class.

When you want to provide utility methods that just deal with your instance, I recommend you use static methods in a non-static class. For example:

var myClass = MyClass.Create();
var myClass = MyClass.Parse("serialized.MyClass");
Share:
19,489
Erkan Y.
Author by

Erkan Y.

Developer, Father, Junior Entrepreneur, Basketball fan, Coffee Enthusiast

Updated on June 05, 2022

Comments

  • Erkan Y.
    Erkan Y. about 2 years

    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

  • Nathan Taylor
    Nathan Taylor over 14 years
    That's kind of a broad answer that is only relevant to C#.
  • JaredPar
    JaredPar over 14 years
    @Nathan the question specifically mentions C# so yep
  • variable
    variable over 2 years
    What is an example of extension method please?