Question:
In C# what is the use of Static Classes?
Randel
2011-03-13 09:19:14 UTC
I know that Static Classes cannot be instantiated, what I want to know is why and when do should I use it?

Why not just create the static members as static variables on top of the main method?
Four answers:
Silent
2011-03-13 09:42:32 UTC
You could get the same effect by just declaring all the members of a class static. However, declaring the class itself static lets the compiler know what you're trying to do. If the class is declared static, any non-static members result in compile errors, and any attempt to instantiate the class results in a compile error. This helps prevent you from accidentally doing the wrong thing with the class.
peteams
2011-03-13 16:47:22 UTC
Most classes it makes sense to create as instances and to derive other classes from. Object is the obvious example, the class from which every other class derives.



Other classes make no sense to either instantiate or to derive from. Consider the Math class, which contains all the usual mathematical functions. All its members are static, so an instance of the class would only have Object's members. As all its members are static, deriving from it has little utility.



Making Math a static class both documents that it is pointless instantiating or deriving from it. More than that it actually prevents you doing so, since doing that demonstrates your probably doing something wrong.



So static classes improve code quality by documenting and imposing true static semantics on the class.
Ken
2011-03-13 19:28:01 UTC
You use static classes when you don't want to associate them with anything else (any other objects).



This is not a perfect illustration; but, maybe it can help:

Someone explained it to me like this (since I have worked a lot with JavaScript):



If you have used JavaScript and have created a separate .js file to hold a big function, that separate page is not associated with any other page. And, it save resources. You don't have to put the function on every page, and it is not associated with any page. It stands by itself and returns values. You just link it to your HTML/ASPX pages.



Here is the MSDN page that explains it:

http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx#Y798

Be sure to select the C# examples.
Metal M
2011-03-13 16:20:26 UTC
to not consume memory resources by creating instance every time you want to use the function in some where


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...