Junior Mayhe
Junior Mayhe

Reputation: 16411

What is better: public static Class with static methods or public Class with static methods?

Regarding class public class declaration, please look at these two pieces of code:

public class Helper
{
    public static void CallMeganFox(string phoneNumber)
    { //...

and

public static class Helper
{
    public static void CallMeganFox(string phoneNumber)
    { //...

What is better to use and why?

Upvotes: 3

Views: 394

Answers (2)

Jon
Jon

Reputation: 437554

It's "better" in theory to make it explicit that this class is not supposed to be instantiated by making it static (second option), because it communicates intent¹.

However in such a simple case, from a practical perspective there will be exactly zero difference². Noone's going to look at this class and try to instantiate it.

¹ As Cody Gray points out, it can also help you catch mistakes earlier (e.g. forgetting to make a helper method static). While that viewpoint certainly has merit, again the practical difference is going to be negligible: the compiler would complain as soon as you tried to call the method statically in any case.

² Actually, this is not always true. For example, the C# compiler will not let you define extension methods in a non-static class -- not because it cannot, but because it wants to nudge you towards a "best practice".

Upvotes: 4

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10522

static class cannot have non-static methods. If that's what you want - then use it.

More information can be found in this SO question and answers.

Upvotes: 1

Related Questions