Thursday 6 February 2020

Explicit Interface Implementation

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. In the following example, all the calls to Paint invoke the same method.



class Test 
{
    static void Main()
    {
        SampleClass sc = new SampleClass();
        IControl ctrl = sc;
        ISurface srfc = sc;

        // The following lines all call the same method.
        sc.Paint();
        ctrl.Paint();
        srfc.Paint();
    }
}

interface IControl
{
    void Paint();
}
interface ISurface
{
    void Paint();
}
class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method. 
    public void Paint()
    {
        Console.WriteLine("Paint method in SampleClass");
    }
}

// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period. For example:
C#
public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
C#
// Call the Paint methods from Main.

SampleClass obj = new SampleClass();
//obj.Paint();  // Compiler error.

IControl c = obj;
c.Paint();  // Calls IControl.Paint on SampleClass.

ISurface s = obj;
s.Paint(); // Calls ISurface.Paint on SampleClass.

// Output:
// IControl.Paint
// ISurface.Paint
Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method:
C#
interface ILeft
{
    int P { get;}
}
interface IRight
{
    int P();
}
To implement both interfaces, a class has to use explicit implementation either for the property P, or the method P, or both, to avoid a compiler error. For example:
C#
class Middle : ILeft, IRight
{
    public int P() { return 0; }
    int ILeft.P { get { return 0; } }
}

Tuesday 7 January 2020

Why do you use a Singleton class if a Static class serves the purpose?


Why do you use a Singleton class if a Static class serves the purpose?

What is the difference between Singleton and Static classes and when do you use each one in your program?


Singleton is a design pattern that makes sure that your application creates only one instance of the class anytime. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.

Why and what is the use of Singleton pattern?

  • To preserve global state of a type.
  • To share common data across application.
  • To reduce overhead of instantiating a heavy object again and again.
  • Suitable for Facades and Service proxies.
  • To cache objects in-memory and reuse them throughout the application.

Example scenarios where Singleton can be used

  • Service Proxies: In an application invoking a service aka API is an extensive operation. And creating a Service client itself time consuming process. By having a Service proxy as a Singleton this overhead can be reduced.
  • Facades: Like service proxy, Database connections are another one example where Singleton can be used to produce better performance and synchronization.
  • Logs: I/O is a heavier operation, by having a single instance of a Logger, required information can be written to same file as logs.
  • Data sharing: Configuration values and any constant values can be kept in Singleton to read by other components of the application.
  • Caching: Data fetching is a time taking process whereas caching required data in the application memory avoids DB calls and Singleton can be used here to handle the caching with thread synchronization in an efficient manner comparing to static type.

Implementation of Singleton pattern

At any point of time the application should hold only one instance of the Singleton type. So in order to achieve it, we should mark the constructor of the type as private member and an method or a property should be exposed to outer world to give the Singleton instance.




When shall we use singleton class and when to go for static classes?

Static classes are basically used when you want to store a single instance, data which should be accessed globally throughout your application. The class will be initialized at any time but mostly it is initialized lazily. Lazy initialization means it is initialized at the last possible moment of time. There is a disadvantage of using static classes. You never can change how it behaves after the class is decorated with the static keyword.

Singleton Class instance can be passed as a parameter to another method whereas static class cannot

The Singleton class does not require you to use the static keyword everywhere. Static class objects cannot be passed as parameters to other methods whereas we can pass instances of a singleton as a parameter to another method.

For example we can modify our normal class to have a method which takes a singleton class instance as a parameter. We cannot do this with static classes.

Singleton classes support Interface inheritance whereas a static class cannot implement an interface:
 static classes cannot implement interfaces.

Static class contains only static members, you cannot inherit or create object of static class. A Singleton class can be inherited and also have base class.

 Singleton vs Static class
  1. Singleton is an object creational design pattern and is designed following some guidelines to ensure it returns only one object of its class whereas static is a reserved keyword in C# which is used before class or method to make it static.
  2. Singleton classes or design pattern can contain static as well as non-static members whereas if a class is marked static, it only should contain static members. For e.g. if a class is static, it should have static methods, static properties and static variables only.
  3. Singleton methods could be passed as a reference to other methods or objects as a parameter but static members could not be passed as a reference.
  4. Singleton objects could be created in a way where they support disposal; that means they could be disposed of.
  5. Singleton objects are stored on heap whereas static objects are stored on the stack.
  6. Singleton objects can be cloned.
  7. Singleton promotes code re-usability and code-sharing and could implement interfaces as well. Singleton can inherit from other classes and promotes inheritance and have better control of object state whereas a static class cannot inherit its instance members.
  8. Singleton class could be designed in a way where it can leverage lazy initialization or asynchronous initialization and is taken into consideration directly by CLR whereas static class is firstly initialized at the time of its first load.
  9. Static classes cannot contain instance constructors and cannot be instantiated whereas the singleton classes have private instance constructor.

 https://codeburst.io/singleton-design-pattern-implementation-in-c-62a8daf3d115

When to use Singleton

Singleton design pattern is a unique design pattern; you cannot find the alternative of Singleton. You can use this when you are creating or using this concept in the application like thread pools, Registry objects, SQL Connection Pools, Objects handling user preferences, Builder classes and Statistics, log4net, etc.

There is one more reason to use Singleton Design Pattern, if you think that your object is large or heavy and takes up a reasonable amount of memory and you make sure that it’s not going to be instantiated multiple times then in that scenario you can use Singleton Design Pattern. A Singleton will help prevent such a case to ever happen.