C# Questions and Answers
C# Questions and Answers
What is a constructor?
A constructor is a class member executed when an instance of the class is created. The constructor
has the same name as the class, and it can be overloaded via different signatures. Constructors are
used for initialization chores.
What is a singleton?
A singleton is a design pattern used when only one instance of an object is created and shared; that
is, it only allows one instance of itself to be created. Any attempt to create another instance simply
returns a reference to the first one. Singleton classes are created by defining all class constructors as
private. In addition, a private static member is created as the same type of the class, along with a
public static member that returns an instance of the class. Here is a basic example:
public class SingletonExample {
private static SingletonExample _Instance;
private SingletonExample () { }
public static SingletonExample GetInstance() {
if (_Instance == null) {
_Instance = new SingletonExample ();
}
return _Instance;
}
}
What is boxing?
Boxing is the process of explicitly converting a value type into a corresponding reference type.
Basically, this involves creating a new object on the heap and placing the value there. Reversing the
process is just as easy with unboxing, which converts the value in an object reference on the heap
into a corresponding value type on the stack. The unboxing process begins by verifying that the
recipient value type is equivalent to the boxed type. If the operation is permitted, the value is copied to
the stack.