Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static classes in c#

In answering this question (https://stackoverflow.com/questions/352317/c-coding-question#352327), it got me wondering...

Is there any danger in regarding a static class as being equivalent to a non-static class instatiation that implements the singleton pattern?

like image 632
spender Avatar asked Dec 09 '08 10:12

spender


People also ask

What is static class and its use?

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the . NET Class Library, the static System.

What does static class means?

A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

Why do we use static classes?

Static class is used when we don't want to create instance of the class. Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.

What is static method in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.


2 Answers

The only thing that seems immediately apparent to me is that a static class is basically just a collection of scoped functions (explicitly avoiding "methods" here) and a singleton is still something you can instantiate, even if you can only have 1. 1 > 0.

You can pass a singleton as an argument to something that expects an object of a certain interface, you cannot pass a static class anywhere (except through some reflection trickery)

like image 192
Kris Avatar answered Oct 26 '22 23:10

Kris


In many ways, a static class and a singleton are similar. One big difference is that a singleton might implement some interfaces, which isn't possible with a static class. For example, Comparer<T>.Default / EqualityComparer<T>.Default provide (via the interface) the ability to use the item in sorting / dictionary usage.

It is also possible (though tricky) to use a singleton with the standard serialization frameworks. With a static class, you'd have to manage any state persistence manually.

like image 23
Marc Gravell Avatar answered Oct 27 '22 01:10

Marc Gravell