A couple of questions re static classes. Some of this is from stuff I have read a while ago so I want to dispell any myths.
I know that if I need one instance of a class, eg like to represent one company (ie company details), the class can be static. Why do I need multiple identical instances?
However:
1) Can the choice of parameters in the methods of a class (ie the type or whether its an instance class/interface etc) , instance or otherwise, affect the decision to make a class static or not? So if I provide an instance object as a parameter (e.g. myMethod(new Car()) ), or anything, can this have any influence on whether to make the class static or not? I read a while back that this can, so I am trying to dispell a myth.
2) If the static class does not use another class's state, does this have any bearing on making a class static?
IE a static class which contains a field, and that field is used within the class's ownn methods.
I also read a post on here about static and a member said that if the class does not contain "repeatable" functionality, it could be made static. What does repeatable mean in this context?
Thanks
No, the type of parameter is wholly irrelevent to the class being static.
No, a method consuming state (or not) has no bearing on whether the method should be static.
I suspect "repeatable" means potentially polymorphic with subclasses and method overriding.
In sum, make the method (or class) static if it will never consume or modify state on its own instance. In other words, if it doesn't make use of this (either explicitly or implied) then it should probably be made static.
Three reasons to make an object not static:
Your object will need to be set to a newly initialized state more than once. You could write a method to do the reinitialization, but Note that although static classes can have a constructor (which I believe is not called until the first reference to a member of the static class triggers the class to be loaded), you can't call it run-time.
You might want to have a 'memento' copy of the object to undo to when the user cancels editing a 'work' copy.
The static object might be accessed from multiple instantiated objects at the same time. I have seen problems from an ASP.NET web application where a static object was used to store user and state data during page load processing that would have been shared between simultaneous page requests from different users.
1) It cannot. Static methods and instance methods can have the very same signatures, concerning argument types.
2) It does not.
Repeatable: This probably refers to the state stored in instances of the class. If you need a storage for a given program state (say, a score) only once, you can use a static class with static fields. If you need that state several times (say, another score for each player), you use instance fields because you can then create as many instances of your class as you need (in this case, as many instances as there are players).
The simple sum-up in my opinion: If it makes sense for all members of a class to be static, then you should mark the class as static. There's not really anything complicated going on here, it's as simple as that.
Related
This question already has answers here:
Class with single method -- best approach?
(15 answers)
Closed 8 years ago.
Here's what MSDN has to say under When to Use Static Classes:
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.
To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static?
I wrote my thoughts of static classes in an earlier Stack Overflow answer:
Class with single method -- best approach?
I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.
Polymorphism
Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.
Interface woes
Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.
Testing
This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.
Fosters blobs
As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.
Parameter creep
To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.
Demanding consumers to create an instance of classes for no reason
One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();
Only a Sith deals in absolutes
Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.
Standards, standards, standards!
Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.
When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more 'bottom-up' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.
On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to 'top-down' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.
Most classes can be represented by either static or non-static, but when you are in doubt just go back to your OOP roots and try to think about what you are representing. Is this an object that is performing an action (a car that can speed up, slow down, turn) or something more abstract (like displaying output).
Get in touch with your inner OOP and you can never go wrong!
For C# 3.0, extension methods may only exist in top-level static classes.
If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.
It is more of a guideline than a rule, really...
Static classes are very useful and have a place, for example libraries.
The best example I can provide is the .Net Math class, a System namespace static class that contains a library of maths functions.
It is like anything else, use the right tool for the job, and if not anything can be abused.
Blankly dismissing static classes as wrong, don't use them, or saying "there can be only one" or none, is as wrong as over using the them.
C#.Net contains a number of static classes that is uses just like the Math class.
So given the correct implementation they are tremendously useful.
We have a static TimeZone class that contains a number of business related timezone functions, there is no need to create multiple instances of the class so much like the Math class it contains a set of globally accesible TimeZone realated functions (methods) in a static class.
I do tend to use static classes for factories. For example, this is the logging class in one of my projects:
public static class Log
{
private static readonly ILoggerFactory _loggerFactory =
IoC.Resolve<ILoggerFactory>();
public static ILogger For<T>(T instance)
{
return For(typeof(T));
}
public static ILogger For(Type type)
{
return _loggerFactory.GetLoggerFor(type);
}
}
You might have even noticed that IoC is called with a static accessor. Most of the time for me, if you can call static methods on a class, that's all you can do so I mark the class as static for extra clarity.
I've started using static classes when I wish to use functions, rather than classes, as my unit of reuse. Previously, I was all about the evil of static classes. However, learning F# has made me see them in a new light.
What do I mean by this? Well, say when working up some super DRY code, I end up with a bunch of one-method classes. I may just pull these methods into a static class and then inject them into dependencies using a delegate. This also plays nicely with my dependency injection (DI) container of choice Autofac.
Of course taking a direct dependency on a static method is still usually evil (there are some non-evil uses).
I use static classes as a means to define "extra functionality" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.
Other than that, I think that "Use a static class as a unit of organization for methods not associated with particular objects." describe quite well their intended usage.
This is another old but very hot question since OOP kicked in.
There are many reasons to use(or not) a static class, of course and most of them have been covered in the multitude of answers.
I will just add my 2 cents to this, saying that, I make a class static, when this class is something that would be unique in the system and that would really make no sense to have any instances of it in the program. However, I reserve this usage for big classes. I never declare such small classes as in the MSDN example as "static" and, certainly, not classes that are going to be members of other classes.
I also like to note that static methods and static classes are two different things to consider. The main disadvantages mentioned in the accepted answer are for static methods. static classes offer the same flexibility as normal classes(where properties and parameters are concerned), and all methods used in them should be relevant to the purpose of the existence of the class.
A good example, in my opinion, of a candidate for a static class is a "FileProcessing" class, that would contain all methods and properties relevant for the program's various objects to perform complex FileProcessing operations. It hardly has any meaning to have more than one instance of this class and being static will make it readily available to everything in your program.
I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.
I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".
Based on MSDN:
You cannot create the instance for static classes
If the class declared as static, member variable should be static for that class
Sealed [Cannot be Inherited]
Cannot contains Instance constructor
Memory Management
Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]
Okay i have a little problem with those 2 things up there
following situation:
I got an abstract class "Emitter". this class has a static Dictionary to keep track of all types deriving from it.
for Example i have the class "LinearEmitter" this class has a static constructor. this constructor adds the typeof(LinearEmitter) to the dictionary. the problem is now, when i want to use the static dictionary from Emitter (static method "getMeEmitterFromID(int id)") it can happen, that the children of "Emitter" (e.g. LinearEmitter) were not initialized (im reading data from a file and then look up the id from the classes in "Emitter" and initialize an instance from that).
how can i make sure that every Child-class is initialized before?(has written itself in the dictionary) ?
of course others should use this library, and they should also use the static constructor to add their Classes to the "Emitter"'s Dictionary
any ideas?
Eric Lippert just had a great series about static constructors.
Static Constructors Part One,
Static Constructors Part Two,
Static Constructors Part Three,
Static Constructors Part Four
To sum the useful bit up in your case: Static constructors get invoked by
just before the first access of a static method/field.
just before the first access to an instance of the type.
So you either invoke a static method like Initialize() or instantiate a class of the type derived from Emitter.
That aside, I'm sure there's a better way to implement your problem because the way static initializers run could change over different .NET / CLR versions and I wouldn't rely on that if you don't have to.
I would not expose the Dictionary itself, but instead make it an implementation detail. Then you can make a method like GetByType(Type typeToGetFromDictionary). Now, the get method can lazily load the pieces it does not already have.
That being said, I agree with the comments that you should possibly rethink the architecture as this might not even be necessary.
This question already has answers here:
Class with single method -- best approach?
(15 answers)
Closed 8 years ago.
Here's what MSDN has to say under When to Use Static Classes:
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.
To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static?
I wrote my thoughts of static classes in an earlier Stack Overflow answer:
Class with single method -- best approach?
I used to love utility classes filled up with static methods. They made a great consolidation of helper methods that would otherwise lie around causing redundancy and maintenance hell. They're very easy to use, no instantiation, no disposal, just fire'n'forget. I guess this was my first unwitting attempt at creating a service-oriented architecture - lots of stateless services that just did their job and nothing else. As a system grows however, dragons be coming.
Polymorphism
Say we have the method UtilityClass.SomeMethod that happily buzzes along. Suddenly we need to change the functionality slightly. Most of the functionality is the same, but we have to change a couple of parts nonetheless. Had it not been a static method, we could make a derivate class and change the method contents as needed. As it's a static method, we can't. Sure, if we just need to add functionality either before or after the old method, we can create a new class and call the old one inside of it - but that's just gross.
Interface woes
Static methods cannot be defined through interfaces for logic reasons. And since we can't override static methods, static classes are useless when we need to pass them around by their interface. This renders us unable to use static classes as part of a strategy pattern. We might patch some issues up by passing delegates instead of interfaces.
Testing
This basically goes hand in hand with the interface woes mentioned above. As our ability of interchanging implementations is very limited, we'll also have trouble replacing production code with test code. Again, we can wrap them up, but it'll require us to change large parts of our code just to be able to accept wrappers instead of the actual objects.
Fosters blobs
As static methods are usually used as utility methods and utility methods usually will have different purposes, we'll quickly end up with a large class filled up with non-coherent functionality - ideally, each class should have a single purpose within the system. I'd much rather have a five times the classes as long as their purposes are well defined.
Parameter creep
To begin with, that little cute and innocent static method might take a single parameter. As functionality grows, a couple of new parameters are added. Soon further parameters are added that are optional, so we create overloads of the method (or just add default values, in languages that support them). Before long, we have a method that takes 10 parameters. Only the first three are really required, parameters 4-7 are optional. But if parameter 6 is specified, 7-9 are required to be filled in as well... Had we created a class with the single purpose of doing what this static method did, we could solve this by taking in the required parameters in the constructor, and allowing the user to set optional values through properties, or methods to set multiple interdependent values at the same time. Also, if a method has grown to this amount of complexity, it most likely needs to be in its own class anyway.
Demanding consumers to create an instance of classes for no reason
One of the most common arguments is: Why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse - although this does make the requirement that your class is stateless. If it's not stateless, you can still create static wrapper methods that handle everything, while still giving you all the benefits in the long run. Finally, you could also make a class that hides the instantiation as if it was a singleton: MyWrapper.Instance is a property that just returns new MyClass();
Only a Sith deals in absolutes
Of course, there are exceptions to my dislike of static methods. True utility classes that do not pose any risk to bloat are excellent cases for static methods - System.Convert as an example. If your project is a one-off with no requirements for future maintenance, the overall architecture really isn't very important - static or non static, doesn't really matter - development speed does, however.
Standards, standards, standards!
Using instance methods does not inhibit you from also using static methods, and vice versa. As long as there's reasoning behind the differentiation and it's standardised. There's nothing worse than looking over a business layer sprawling with different implementation methods.
When deciding whether to make a class static or non-static you need to look at what information you are trying to represent. This entails a more 'bottom-up' style of programming where you focus on the data you are representing first. Is the class you are writing a real-world object like a rock, or a chair? These things are physical and have physical attributes such as color, weight which tells you that you may want to instantiate multiple objects with different properties. I may want a black chair AND a red chair at the same time. If you ever need two configurations at the same time then you instantly know you will want to instantiate it as an object so each object can be unique and exist at the same time.
On the other end, static functions tend to lend more to actions which do not belong to a real-world object or an object that you can easily represent. Remember that C#'s predecessors are C++ and C where you can just define global functions that do not exist in a class. This lends more to 'top-down' programming. Static methods can be used for these cases where it doesn't make sense that an 'object' performs the task. By forcing you to use classes this just makes it easier to group related functionality which helps you create more maintainable code.
Most classes can be represented by either static or non-static, but when you are in doubt just go back to your OOP roots and try to think about what you are representing. Is this an object that is performing an action (a car that can speed up, slow down, turn) or something more abstract (like displaying output).
Get in touch with your inner OOP and you can never go wrong!
For C# 3.0, extension methods may only exist in top-level static classes.
If you use code analysis tools (e.g. FxCop), it will recommend that you mark a method static if that method don't access instance data. The rationale is that there is a performance gain. MSDN: CA1822 - Mark members as static.
It is more of a guideline than a rule, really...
Static classes are very useful and have a place, for example libraries.
The best example I can provide is the .Net Math class, a System namespace static class that contains a library of maths functions.
It is like anything else, use the right tool for the job, and if not anything can be abused.
Blankly dismissing static classes as wrong, don't use them, or saying "there can be only one" or none, is as wrong as over using the them.
C#.Net contains a number of static classes that is uses just like the Math class.
So given the correct implementation they are tremendously useful.
We have a static TimeZone class that contains a number of business related timezone functions, there is no need to create multiple instances of the class so much like the Math class it contains a set of globally accesible TimeZone realated functions (methods) in a static class.
I do tend to use static classes for factories. For example, this is the logging class in one of my projects:
public static class Log
{
private static readonly ILoggerFactory _loggerFactory =
IoC.Resolve<ILoggerFactory>();
public static ILogger For<T>(T instance)
{
return For(typeof(T));
}
public static ILogger For(Type type)
{
return _loggerFactory.GetLoggerFor(type);
}
}
You might have even noticed that IoC is called with a static accessor. Most of the time for me, if you can call static methods on a class, that's all you can do so I mark the class as static for extra clarity.
I've started using static classes when I wish to use functions, rather than classes, as my unit of reuse. Previously, I was all about the evil of static classes. However, learning F# has made me see them in a new light.
What do I mean by this? Well, say when working up some super DRY code, I end up with a bunch of one-method classes. I may just pull these methods into a static class and then inject them into dependencies using a delegate. This also plays nicely with my dependency injection (DI) container of choice Autofac.
Of course taking a direct dependency on a static method is still usually evil (there are some non-evil uses).
I use static classes as a means to define "extra functionality" that an object of a given type could use under a specific context. Usually they turn out to be utility classes.
Other than that, I think that "Use a static class as a unit of organization for methods not associated with particular objects." describe quite well their intended usage.
This is another old but very hot question since OOP kicked in.
There are many reasons to use(or not) a static class, of course and most of them have been covered in the multitude of answers.
I will just add my 2 cents to this, saying that, I make a class static, when this class is something that would be unique in the system and that would really make no sense to have any instances of it in the program. However, I reserve this usage for big classes. I never declare such small classes as in the MSDN example as "static" and, certainly, not classes that are going to be members of other classes.
I also like to note that static methods and static classes are two different things to consider. The main disadvantages mentioned in the accepted answer are for static methods. static classes offer the same flexibility as normal classes(where properties and parameters are concerned), and all methods used in them should be relevant to the purpose of the existence of the class.
A good example, in my opinion, of a candidate for a static class is a "FileProcessing" class, that would contain all methods and properties relevant for the program's various objects to perform complex FileProcessing operations. It hardly has any meaning to have more than one instance of this class and being static will make it readily available to everything in your program.
I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.
I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".
Based on MSDN:
You cannot create the instance for static classes
If the class declared as static, member variable should be static for that class
Sealed [Cannot be Inherited]
Cannot contains Instance constructor
Memory Management
Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]
So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.
One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:
var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");
As for static fields, is creating singelton-objects their best use?
Static methods are usually useful for operations that don't require any data from an instance of the class (from this) and can perform their intended purpose solely using their arguments.
A simple example of this would be a method Point::distance(Point a, Point b); that calculates the distance between two points and don't require an instance.
Static fields are useful among others for constants that don't change all that often and are used by all the instances of a class.
It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.
EDIT: From stevemegson in the comments
A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.
I would say use static methods whenever you have functions which are independent of the state of the instance, ie. doesn't depend on any instance fields.
The less non-local state that a method depends on, the easier it is to understand, so static is a helpful signal to the reader of the code.
I keep it clear by remembering that instance methods work on/inside individual objects while static methods do something for the Class.
In the case of LoadFromFile(), you want a static method because you want a null reference if the load fails - the instance doesn't exist yet. If you implemented it as a constructor, you'd have to throw an Exception on failure.
Other good uses for statics: Compare(obj a, obj b), Delete(obj a) for data objects (an object can't delete itself since its reference is still around), or static Classes for procedural code that honestly can't be modeled in an object.
Use a static method when the method does not belong to a specific object.
For example, if you look at the Math class in .NET framework, you will see
that all methods are static. Why? Because there is no reason to must create
an object to use the methods. Why would you want to create an object of the
Math class, when all you want is the absolute value of something? No, there
is no reason to do this, and therefore, the method is static.
So when you design a class, ask yourself:
Does this method belong to an object, or the class itself?
A method belongs to an object, if it modifies the state of the object. If
the method does not modify a specific object, it can most likely be static.
Another example, suppose that you want to know how many objects of a class
that is created (don't ask me why...). For this task, you could create a
static method GetNumberOfObjects() (and you obviously need a static field,
and some code in the constructor too). Why would i have it static, you might
ask. Well, answer the above question, and you will see. The method does not
belong to any specific object. Additionally, it does not modify any object.
I hope this makes sense.
You should use static methods whenever you have a function that does not depend on a particular object of that class.
There is no harm in adding the static keyword: it will not break any of the code that referred to it. So for example, the following code is valid whether or not you have the 'static' keyword:
class Foo
{
public Foo(){}
public static void bar(){} // valid with or without 'static'
public void nonStatic(){ bar(); }
}
...
Foo a = new Foo();
a.bar();
So you should add 'static' to whatever methods you can.
Here are some examples of when you might want to use static methods:
1) When the function doesn't make use of any member variables. You don't have to use a static method here, but it usually helps if you do.
2) When using factory methods to create objects. They are particularly necessary if you don't know the type to be created in advance: e.g.
class AbstractClass {
static createObject(int i) {
if (i==1) {
return new ConcreteClass1();
} else if (i==2) {
return new ConcreteClass2();
}
}
}
3) When you are controlling, or otherwise keeping track of, the number of instantiations of the class. The Singleton is the most used example of this.
4) When declaring constants.
5) Operations such as sorts or comparisons that operate on multiple objects of a class and are not tied to any particular instance.
6) When special handling has to be done before the first instantiation of an object.
You may use static methods when the client of the class do not have an instance of the class to work with. For instance the Singleton design pattern is used to ensure that only one instance of a class exist in the system. It requires that the constructors of the Singleton be private so that no instances can be created by the client.
So if you cannot create an instance how do you access the instance methods of the class? By calling a static method that returns the Singleton instance of the class.
This is of course just one scenario but there are many others.
What is the use of a static class?
I mean what are benefits of using static class and how CLR deals with static classes?
A static class simply denotes that you don't expect or need an instance. This is useful for utility logic, where the code is not object-specific. For example, extension methods can only be written in a static class.
Pre C# 2.0, you could just have a regular class with a private constructor; but static makes it formal that you can never have an instance (there is no constructor*, and all members must be static).
(*=see comment chain; you can optionally have a type initializer (static constructor aka .cctor), but you cannot have an instance constructor (aka .ctor)).
The compilation and metadata model for .net requires that all functions are defined within a class. This makes life somewhat easier and simpler for the reflection api's since the concepts of the owning class and its visibility is well defined. It also makes the il model simpler.
since this precludes free functions (ones not associated with a class) this makes the choice of where to put functions which have no associated state (and thus need for an instance). If they need no state associated with them nor have any clear instance based class to which they can be associated and thus defined within there needs to be some idiom for their definition.
Previously the best way was to define the methods within a class whose constructor was private and have none of the functions within the class construct it.
This is a little messy (since it doesn't make it crystal clear why it was done without comments) and the reflection api can still find the constructor and invoke it.
Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. Static classes have no constructor at all.
A static class is a language hack to write procedural programs in C#.
All members of a static class has to be static members, so, if you forget to add 'static' before any of them your code won't compile, it also makes your code more readable as anyone who will see that the class is static will understand it only contains static members.
The best use for a static class is for utility functions, you could also use them to keep the global methods and data in your application, I use static static classes very often in almost any project.
Static classes are often used to group related global services which you initially don't want to be accessed with an object instance. An example is the Math class in the .Net BCL, which you use directly, e.g., Math.Sqrt(10.0)
Static classes are sealed. This may be a useful option to use static for utility classes.
I got clear idea from this statements.
To know more about static class. First we must differentiate between static and instance data first.
Each time you create a new instance of a class you get a new copy of the instance data to play with. The instance methods of the class work on the instance data. The instance data is completely independent of the instance data in all other classes and even instances of the same class. If you change a value in one instance it has no impact on the same value in other instances. The bulk of program data is instance data.
Static data is equivalent to global data. Everybody in the program sees the same data. If someone changes the data then everybody else will see the change as well. Static data is useful for sharing information across a program such as database connection strings or log files. There is only one copy of static data in memory in general. (There are exceptions such as when dealing with multiple appdomains).
When you create an instance of a class you are effectively allocating some memory to hold your own copy of the instance data defined by the class. If you create 5 instances of a class then you get 5 separate memory locations where each location has its own copy of the instance data. Each memory block is independent of the others.
If a class has no instance data then it doesn't make any sense to create instances of it. Doing so is harmless but also a waste of time. This is where static classes come in. A static class is a way to identify a class as having no instance data. By marking the class as static you are telling the compiler that all the data in the class is shared across the board. As a result the compiler enforces some rules to make things clear. A static class can only contain static members. A static class cannot be instantiated. A static class must be sealed. The compiler enforces this for convenience of the developers.
A static class is sealed. This is because static classes cannot have per-instance data.
Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static constructor is called once and the static class remains in the memory for the lifetime of the application domain in which your program resides.
Reference: http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx
1.First of all u cannot create the instance for static classes
If the class declared as static, member variable should be static for that class
3.Sealed [Cannot be Inherited]
4.Cannot contains Instance constructor
5.Memory Management
Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]
In a class we declare a function as static,only if that function is not associated to any objects. We should not use "this" operator in that static function, because "this" operator will refers to object which invoke the function. Eg: Consider a class named Employee has few variables like Name, Age, Department, in this Employee class i am going to add a function called getSimilarNames() that will show How many employees having similar names. This function need not to be associated to any Employees. So I declare this function as a Static.If a class that only contains static functions, we declare that class is a static class. The Static function improves performance.