32

Possible Duplicate:
When to Use Static Classes in C#

I set my classes as static a lot, but I am not sure when use static or not, or what's the difference it makes to use it or not.

can anybody explain please?

Community
  • 1
  • 1
ShadowG
  • 683
  • 2
  • 10
  • 21
  • 2
    static classes/methods are for example useful to implement the Singleton pattern and the Factory pattern... – Yahia Oct 28 '11 at 18:55
  • 2
    @Yahia: Singleton pattern with static classes? [I don't think so.](http://stackoverflow.com/questions/3565482/can-singleton-class-be-static/3565496#3565496) – BoltClock Oct 28 '11 at 18:56
  • @BoltClock IF you read carefully then I wrote "static classes/methods" and I am pretty sure static methods are usefull when implementing a Singleton pattern... – Yahia Oct 28 '11 at 18:59

3 Answers3

34

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

Dylan Smith
  • 22,069
  • 2
  • 47
  • 62
  • 6
    Why is it a good practice to make the class as static if we have all members as static? What will be the advantage of making the class itself as static? – Mayur Dhingra Dec 17 '13 at 08:38
  • 2
    It will prevent people from trying to instantiate it – Dylan Smith Dec 17 '13 at 14:06
  • 6
    But for that purpose, you can declare a private constructor and make the class Singleton. As far as I know, a static class will always remain in the memory creating an overhead but normal singleton classes will not. – Mayur Dhingra Jan 28 '14 at 12:34
  • @DylanSmith and Why is it a good practice to prevent people from trying to instantiate it , the real question is why is it good to use a static methode or a static classe ??? – akira Sep 26 '18 at 15:25
  • In general I try to avoid static methods for test ability purposes. But if you have a class that only contains static methods, consumers of that class shouldn’t be instantiating it, because it’s pointless. Making it a static class will allow the compiler to tell that developer that they are doing something they shouldn’t. – Dylan Smith Oct 03 '18 at 20:05
20

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
  • compulsorily compulsorily compulsorily compulsorily compulsorily compulsorily – Alex Gordon Oct 17 '13 at 18:00
  • 1
    I know this answer was from a long time ago, but static classes actually can have static constructors. Just FYI. They are used for initial instantiation of values if you so choose to partake. – dyslexicanaboko May 03 '19 at 21:55
3

Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.

As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.

The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.

Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.

One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,

public class Foo
{
    public static Foo New(string fooString)
    {
        ProxyGenerator generator = new ProxyGenerator();

        return (Foo)generator.CreateClassProxy
             (typeof(Foo), new object[] { fooString }, new Interceptor()); 
    }

This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

Sean Thoman
  • 7,429
  • 6
  • 56
  • 103