3

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?

Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161

2 Answers2

4

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".

Jon
  • 428,835
  • 81
  • 738
  • 806
1

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.

Community
  • 1
  • 1
Sergey Kudriavtsev
  • 10,328
  • 4
  • 43
  • 68