-8

What's the difference between static classes, and static methods? I want to learn the differences, and when I might use one vs. the other.

For example, I have a class like this:

static class ABC
{
    public int a; 
    public void function_a()
    {
        a = 10;
    }
}

and another class like this:

class DEF
{
    public static int a;
    public static void function_a()
    {
        a= 10;
    }
}

I have used the second type of class many times, and I know the usage. What's the usage of the first example?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
james raygan
  • 681
  • 5
  • 10
  • 28
  • 6
    Your first example doesn't even compile and doesn't appear to do anything interesting, so describing what it is for seems impossible. This question is too vague to answer. – Eric Lippert Jul 23 '13 at 01:51
  • You can only have static members in a static class. Your first example is composed of instance members. – pcnThird Jul 23 '13 at 01:52
  • `GOOGLE IS A GOOD TOOL- Use it sometime` http://stackoverflow.com/questions/2267371/static-method-of-a-static-class-vs-static-method-of-a-non-static-class-c-shar – MethodMan Jul 23 '13 at 01:52

1 Answers1

3

Your first example will not compile, a static class must have all static members.

The difference between just using some static methods and a static class is that you are telling the compiler that the class cannot be instantiated. The second example you can create an object of the DEF class even though there are no instance methods in it. The ABC class cannot be instantiated with the new operator (will get a compile-time error).

When to Use Static Classes

Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.

C#

 class CompanyInfo
{
    public string GetCompanyName() { return "CompanyName"; }
    public string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can declare it as a static class, like this:

C#

 static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}

Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.

ggcodes
  • 2,859
  • 6
  • 21
  • 34