Featured Post

Monday, April 24, 2017

What is Singleton?


The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.
There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version.
All these implementations share four common characteristics, however:
  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}
This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.
Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}
As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:
  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have an article with more details about this issue. Also note that it affects performance, as discussed near the bottom of the page.
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }
       
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Sixth version - using .NET 4's Lazy<T> type

If you're using .NET 4 (or higher), you can use the System.Lazy<T> type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
   
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

What Are Generics


Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the < and > brackets, enclosing a generic type parameter.
(E.G)
// Declare the generic class.
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

Benefits:

Ø  Use generic types to maximize code reuse, type safety, and performance.
Ø  The most common use of generics is to create collection classes.
Ø  The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible instead of classes such as ArrayList in the System.Collections namespace.
Ø  You can create your own generic interfaces, classes, methods, events and delegates.
Ø  Generic classes may be constrained to enable access to methods on particular data types.
Ø  Information on the types that are used in a generic data type may be obtained at run-time by using reflection.



Introduction to access modifiers

Introduction

Classes and structs can be restricted so that only the program or namespace they are declared in may use them. Class members can be restricted so that only derived classes can use them, or restricted so that only classes within the current namespace or program can use them. Access modifiers are keywords added to the class, struct, or member declaration to specify these restrictions. So in a nutshell access modifiers are keywords which control the visibility of class members and other code constructs.

The access modifiers in .NET are

1. Public

2. Private

3. Protected

4. Internal

5. Protected internal
           
Public

Public means visible to everyone and everywhere.

Access cases
1. By objects of the class

2. By derived classes

Private

Private means hidden and usable only by the class itself. No code using a class instance can access a private member and neither can a derived class. Information or functionality that will not be needed or has no meaning outside of the context of a specific class should be made private.

Access cases
1. Cannot be accessed by object

2. Cannot be accessed by derived classes

protected

Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.

Access cases
1. Cannot be accessed by object

2. By derived classes

Internal

Internal are public to the entire assembly but private to any outside assemblies. Internal is useful when you don't want to allow other assemblies to have the functionality.

Access cases

In same assembly (public).
1. By objects of the class

2. By derived classes
In other assembly (internal)
1. Cannot be accessed by object

2. Cannot be accessed by derived classes

Protected internal

finally, we have the only compound access modifier allowed in .NET. Members marked as protected internal may be accessed only by a descendant class that's contained in the same assembly as its base class
http://kona.kontera.com/javascript/lib/imgs/grey_loader.gif
. You use protected internal in situations where you want to deny access to parts of a class' functionality to any descendant classes found in other applications.

Note: that it's illegal to combine two access modifiers for a class but can only be applied to the members.

Access cases

in same assembly (protected).

  1. Cannot be accessed by object
  2. Can be accessed by a derived classes
In other assembly (internal)
1. Cannot be accessed by object

2. Cannot be accessed by derived classes

Point to remember

Interface and enumeration members are always public and no access modifiers are needed (or allowed).

Classes
http://kona.kontera.com/javascript/lib/imgs/grey_loader.gif
in namespaces are internal by default and may be either internal or public but cannot be private or protected, while namespaces themselves are always public.

Members of a struct are private by default and may be given public, internal, or private access modifiers.

To summarize it

Code:
+------------------+---------+-----------+--------+----------+--------------------+
|                  | private | protected | public | internal | protected internal |
+------------------+---------+-----------+--------+----------+--------------------+
| By object        | No      | No        | Yes    | Yes      | No                 |
+------------------+---------+-----------+--------+----------+--------------------+
| By derived class | No      | Yes       | Yes    | Yes      | Yes(Same assembly) |
+------------------+---------+-----------+--------+----------+--------------------+


Note: BY default the access is internal for classes if no access modifier is added.

Sunday, April 23, 2017

Object Oriented Programming Concepts and questions

Points that we will cover in this post:
  • OOP's overview
  • Classes and Objects
  • Constructor and Destructor
  • Function Overloading
  • Encapsulation
  • Inheritance
  • Interface
  • Polymorphism
OOP's overview
Object-oriented programming (OOP) is the core element of the .NET framework.
The fundamental idea behind OOP is to combine data and methods that operate on that data into a single unit and such units are called an object. All OOP languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, polymorphism and reusability. Let's now take a brief look at these concepts.

Class
A class is a template for creating different objects which defines its properties and behaviors. A class can contain fields and methods to describe the behavior of an object. It is the blue print that describes objects.

Class members
A class has different members, and developers in Microsoft suggest to program them in the following order:
  • Namespace: The namespace is a keyword that defines a distinct name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.
  • Class declaration: Line of code where the class name and type are defined.
  • Fields: Set of variables declared in a class block.
  • Constants: Set of constants declared in a class block.
  • Constructors: A method or group of methods that contains code to initialize the class.
  • Properties: The set of descriptive data of an object.
  • Events: Program responses that get fired after a user or application action.
  • Methods: Set of functions of the class.
  • Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.
Access keywords
Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:
  • Public: Allows access to the class member from any other class.
  • Private: Allows access to the class member only in the same class.
  • Protected: Allows access to the class member only within the same class and from inherited classes.
  • Internal: Allows access to the class member only in the same assembly.
  • Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
  • Static: Indicates that the member can be called without first instantiating the class.
The following sample code illustrates a sample class in C#:
///Imported namespaces
using System;
/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {
///Class declaration
public class employee {
///Fields
private string _name;
private int _salary;
///Constants
private const int anualBonus = 1000;
///Constructor
public employee(){
}
///Properties
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
public int Salary {
get {
return _salary;
}
set {
_salary = value;
}
}
/// Event handlers
public event EventHandler OnPromotion {
add {
}
remove {
}
}
/// Methods
public void DuplicateSalary()
{
_salary = _salary*2;
}
}
}


Object
Object is an instance of a class. We can perform set of operations and access properties of class using object.

Structures
Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

What is Abstraction?     
Where we use abstract?
How Data hiding is different from abstraction.  

Encapsulation and abstraction:
Encapsulation and abstraction is the advanced mechanism in C# that lets your program to hide unwanted code within a capsule and shows only essential features of an object. Encapsulation is used to hide its members from outside class or interface, whereas abstraction is used to show only essential features.
In C# programming, Encapsulation uses five types of modifier to encapsulate data. These modifiers are public, private, and internal, protected and protected internal. These all includes different types of characteristics and makes different types of boundary of code.

Encapsulation is the process of hiding irrelevant data from the user. To understand encapsulation, consider an example of mobile phone. Whenever you buy a mobile, you don’t see how circuit board works. You are also not interested to know how digital signal converts into analog signal and vice versa. These are the irrelevant information for the mobile user, that’s why it is encapsulated inside a cabinet.

Abstraction is just opposite of Encapsulation. Abstraction is mechanism to show only relevant data to the user. Consider the same mobile example again. Whenever you buy a mobile phone, you see their different types of functionalities as camera, mp3 player, calling function, recording function, multimedia etc. It is abstraction, because you are seeing only relevant information instead of their internal engineering.
Inheritance
It means "Reusability". Inheritance is the process by which one object can import the properties of another object.
If we want to use the functionality of one class in to other class then we can inherit this class. Then function and properties of this class will be accessible in child class.
For example all .NET classes inherit from the System.Object class, so a class can include new functionality as well as use the existing object's class functions and properties as well.

C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. This is not allowed in C#. This will lead to a compile time 

What is Polymorphism?
Overloading and overriding difference?
Polymorphism means many forms (ability to take more than one form). In Polymorphism poly means “multiple” and morph means “forms” so polymorphism means many forms.
In polymorphism we will declare methods with same name and different parameters in same class or methods with same name and same parameters in different classes. Polymorphism has ability to provide different implementation of methods that are implemented with same name.
In Polymorphism we have 2 different types those are
        -   Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)
        -   Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)
Compile Time Polymorphism
Compile time polymorphism means we will declare methods with same name but different signatures because of this we will perform different tasks with same method name. This compile time polymorphism also called as early binding or method overloading.

Method Overloading or compile time polymorphism means same method names with different signatures (different parameters)
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}

In above class we have two methods with same name but having different input parameters this is called method overloading or compile time polymorphism or early binding. 

Run Time Polymorphism
Run time polymorphism also called as late binding or method overriding or dynamic polymorphism. Run time polymorphism or method overriding means same method names with same signatures.
In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.
In base class if we declare methods with virtual keyword then only we can override those methods in derived class using override keyword
//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}

Reusability

once a class has been written, created and debugged, it can be distributed to other programmers for use in their own program. This is called reusability, or in .NET terminology this concept is called a component or a DLL. In OOP, however, inheritance provides an important extension to the idea of reusability. A programmer can use an existing class and without modifying it, add additional features to it.

Partial classes:
A partial class splits the definition of a class over two or more source files. You can create a class definition in multiple files but it will be compiled as one class.
Suppose you have a "Person" class. That definition is divided into the two source files "Person1.cs" and "Person2.cs". Then these two files have a class that is a partial class. You compile the source code, then create a single class.
Here is a list of some of the advantages of partial classes: 
  1. You can separate UI design code and business logic code so that it is easy to read and understand. For example, you are developing a web application using Visual Studio and add a new web form then there are two source files, "aspx.cs" and "aspx.designer.cs". These two files have the same class with the partial keyword. The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has user interface control definition.
  2. When working with automatically generated source, the code can be added to the class without having to recreate the source file. For example, you are working with LINQ to SQL and create a DBML file. Now when you drag and drop a table, it creates a partial class in designer.cs and all table columns have properties in the class. You need more columns in this table to bind on the UI grid but you don't want to add a new column to the database table so you can create a separate source file for this class that has a new property for that column and it will be a partial class. So that does affect the mapping between database table and DBML entity but you can easily get an extra field. It means you can write the code on your own without messing with the system generated code.
  3. More than one developer can simultaneously write the code for the class.
  4. You can maintain your application better by compacting large classes. Suppose you have a class that has multiple interfaces so you can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class. Let's see the following code snippet.
5.  public interface IRegister
6.  {
7.      //Register related function
8.  }
9.   
10.public interface ILogin
11.{
12.    //Login related function
13.}
14. 
15.//UserRegister.cs file
16.public partial classUser : IRegister, ILogin
17.{
18.    //implements IRegister interface
19.} 
20. 
21.//UserLogin.cs file
22.public partial classUser
23.{
24.    //implements ILogin interface
25.}
 

A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.

What are Static classes? 

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:
UtilityClass.MethodA();
 
As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides. 
As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides. 
The following list provides the main features of a static class:
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization. For more information, see Static Constructors (C# Programming Guide).
A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.
C# does not support static local variables (variables that are declared in method scope).

Can we have non static function in static class?
Answer is no

Can we constructor in static classes?
Yes only static constructor. But this class will be never instantiated

Can we have private constructor?
Yes, by doing this means it cannot be instantiated.

Are private class members inherited to the derived class?
Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.

Interface:
The Interface is basically a contract between an Interface and a class. In the Interface we do not have implementation of properties and methods.
The class that implements the Interface or inherits from the Interface must implement the methods defined in the Interface.

Abstract classes:
If we need to provide common fields and members to all subclasses, we create an Abstract class. We can create an abstract class, with the use of the abstract keyword. Abstract classes cannot be instantiated.

Difference between interface and abstract class

  •              Interfaces supports multiple inheritance. A class may inherit several interfaces but can only  one abstract class.
  •            We can declare method in interfaces. But in abstract classes we can define and declare methods
  •             Interface are public to all sub classes we cannot use access modifiers. An abstract class can contain access modifiers for the subs, functions, properties.
  •             If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
  •             Abstract classes are generally fast to find actual methods
  •             No fields can be defined in interfaces. And abstract class can have fields.


When to prefer an Abstract class

Abstract classes allow you to provide default functionality for the subclasses. Common knowledge at this point. Why is this extremely important though? If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class. Why? Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if it’s just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the client’s code.

Constructors and Destructors:

Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
  • Constructors and destructors do not have return types nor can they return values.
  • References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
  • Constructors cannot be declared with the keyword virtual.
  • Constructors and destructors cannot be declared const, or volatile.
  • Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.
Example of Constructor

class C
{
       private int x;    
       private int y;
       public C (int i, int j)
       {
                 x = i;
                 y = j;
       }
       public void display ()     
       {
               Console.WriteLine(x + "i+" + y);
       }
}



Example of Destructor



class D
{
        public D ()
        {
            // constructor
        }         
        ~D ()
        {
           // Destructor
        }
}
 

Behavior of Constructors in Inheritance:
The sequence of execution will be first base class constructor will be executed and then derived class constructor

Static Constructors:

This is a new concept introduced in C#. By new here I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
Notes for Static Constructors:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Delegates:
Delegates are function pointers. This Refers to a function. Delegates are simply objects which are holding reference of a method. And we will invoke this delegate it automatically invoke the functions.
As the delegate refers to a method, the same delegates can be used to call multiple methods just by changing the method name at the run time; provided the method (instance or static) match the signature and return type.
Use a delegate when:
    •        An eventing design pattern is used.
    •          It is desirable to encapsulate a static method.
    •    The caller has no need access other properties, methods, or interfaces on the object implementing the method.
    •          Easy composition is desired.
    •           A class may need more than one implementation of the method.
Questions:

New keyword can we use new keyword with function and over ridable function
New methods are expected to hide base methods. The new modifier specifies that a method is supposed to hide a base method. It eliminates a warning issued by the compiler. No functionality is changed. But an annoying warning is silenced.
Here’s a simple implementation in C# without using any keyword. Do you think it will run fine or show some RUN or COMPILE time errors?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics
{
    class A
    {
        public void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

    class Polymorphism
    {
        public static void Main()
        {
            A a1 = new A();
            a1.show();
            B b1 = new B();
            b1.show();
            A a2 = new B();
            a2.show();

        }
    }
}


It is showing some sort of output which means there is neither run time nor compile time error. But it will definitely show a Warning to you in your Visual Studio. So what is it and how to remove it. Do you want to know?
Overriding + Hiding | Together
In this snippet, I show how both these methods can work together in the same snippet. So just go through this and guess the output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Generics
{
    class A
    {
        public virtual void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }
 
    class B : A
    {
        public override void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }
 
    class C : B
    {
        public new void show()
        {
            Console.WriteLine("Am Here!");
            Console.ReadLine();
        }
    }
 
    class Polymorphism
    {
        public static void Main()
        {
            A a1 = new A();
            a1.show();
            B b1 = new B();
            b1.show();
            C c1 = new C();
            c1.show();
            A a2 = new B();
            a2.show();
            A a3 = new C();
            a3.show();
            B b3 = new C();
            b3.show();
        }
    }
}
 
Output will be:
 
Yes we use new keyword with virtual mathode 
https://msdn.microsoft.com/en-us/library/ms173153.aspx