Showing posts with label Interfaces. Show all posts
Showing posts with label Interfaces. Show all posts

Tuesday, April 2, 2019

Interface vs Abstract Class in C#


Feature
Interface
Abstract Class
Definition
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modifiers

Everything Public
Can have public, private, internal for any method  , function.
Adding functionality (Versioning)


If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
When to use
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.

Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.


Monday, December 4, 2017

Same Method name in 2 interfaces, Implemented in one class

This is a tricky Question,  if I create 2 interface with same method name, and implement both in one class. Now if create object of this derived class, which method it will pick-up/Execute at run time.

To test this need to create 2 interface with same method Name.

 interface IFace1
    {
        void GetFaceDetails();
    }

    interface IFace2
    {
        void GetFaceDetails();
    }

Now create a class to implement both interfaces

public class DerivedClass : IFace1, IFace2
    {
        public DerivedClass()
        {
            Console.WriteLine(" Constructor Called. ");
        }
       void IFace1.GetFaceDetails()
        {
            Console.WriteLine(" IFace1.GetFaceDetails ");
        }
        void IFace2.GetFaceDetails()
        {
            Console.WriteLine(" IFace2.GetFaceDetails ");
        }
    }


Now to use this if I create an object of IFace1 then It will call IFace1.GetFaceDetails Method.
IFace1 obj1 = new DerivedClass();
            obj1.GetFaceDetails();

So it will print " IFace1.GetFaceDetails "

Similarly if I  create an object of IFace2 then It will call IFace2.GetFaceDetails Method.
IFace2 obj2 = new DerivedClass();
            obj2.GetFaceDetails();

So it will print " IFace2.GetFaceDetails "


Now what if I create an object of DerivedClass itself.
DerivedClass obj = new DerivedClass();
obj.GetFaceDetails();


In above code it will show a compiler error that GetFaceDetails Method doesn’t exists in DerivedClass. So it will not execute at all. Or you will have to create another method with same name in class, and compiler will pick that method in execution.