tags:

views:

215

answers:

5

I have come across a class which is non-static, but all the methods and variables are static. Eg:

public class Class1 {

    private static string String1 = "one";
    private static string String2 = "two";

    public static void PrintStrings(string str1, string str2)
    {
       ...

All the variables are static across all instances, so there is no point having separate instances of the class.

Is there any reason to create a class such as this?

+4  A: 

No. Make it a static class.

Marcelo Cantos
+15  A: 

Was the class written back in the .NET 1.x days? Static classes didn't appear until C# 2.0.

Matt Hamilton
And in my experince, even with .NET 2.0 or later, many devs forgot to use that keyword on such a class!
Daniel Renshaw
Heck, even Visual Studio forgets! Check out the "Program" class when you start a new console app!
Matt Hamilton
A: 

No, if there are no instance members in the class then it should be static.

David Neale
+4  A: 

No. Some people dont realise that classes themselves can be static, and so don't include in the class definition. This is useful because it provides better intellisense options and ensures that future methods are added statically.

This also implicitly seals the class.

James Westgate
A: 

Static class provide :

  • Contains only static members.

  • Cannot be instantiated.

  • Is sealed.

  • Cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor.

Rajesh
It couldn't be the same as "creating a class that contains only static members and a private constructor" because such a class would need to be instantiated. A static class does not.
Craig Johnston
@Craig You are right. I updated myself :)
Rajesh