This is interview question which is asked in many interviews.
Let’s see what Singleton is.
Singleton is design pattern, which allow user to create singleton
instance of class.
public sealed class Singleton
{
public static Singleton singleton = null;
private Singleton(){}
public static Singleton GetSingletonInstance()
{
if (singleton == null)
{
return new Singleton();
}
else
{
return null;
}
}
}
Here Singleton is a class and
it is marked as sealed, so it should not be
Inherited by any other
classes.
Constructor is private, so object of Singleton class cannot be
created outside of this Singleton class.
GetSingletoninstance is method which returns instance of class.
Singleton:
- It can inherit any other class.
- It can override any methods.
- It can implement interface.
- Single Instance of class can be created.
- It can be passed to methods.
- All methods are not static.
namespace ConsoleApp3
{
//Interface which will be
implemented by Singleton class
public interface IInterface
{
public void SHow();
}
// Singleton class inherit this
MyClass
public class MyClass
{
public void Disp()
{
Console.WriteLine("Disp");
}
}
public sealed class Singleton: MyClass, IInterface
{
public static
Singleton singleton = null;
private Singleton(){}
//All methods are not static. Disp() is
non static method.
public void Disp()
{
Console.WriteLine(“Disp”);
}
public static
Singleton GetSingletonInstance()
{
if (singleton == null)
{
return new
Singleton();
}
else
{
return null;
}
}
//Passing singleton instance to class
public void
Go(Singleton singleton)
{
singleton.Disp();
}
}
Static Class:
- Static class is Loaded by CLR.
- It will be there in memory until
application is running.
- Instance of static class cannot be
created.
See in below image, it is throwing error when I am trying to create instance
of static class MyClass.
- It cannot inherit any other class.
-
- It cannot be inherited by any other
class.
- It cannot override method since static
class cannot inherit any other class.
- Static class cannot be passed to method
parameters.
- Instance of static class cannot be created, hence cannot be passed to
method parameter.
- It cannot be disposed.