Wednesday, 13 July 2016

Interface

http://www.dotnet-tricks.com/Tutorial/csharp/5T27291013-A-Deep-Dive-into-C


http://csharptopicwiseques.blogspot.in/2010/08/interface-ques.html



An interface acts as a contract between itself and any class or struct which implements it. It means a class that implement an interface is bound to implement all its members. Interface has only member’s declaration or signature and implicitly every member of an interface is public and abstract.

For example, the most common use of interfaces is, within SOA (Service Oriented Architecture). In SOA (WCF), a service is exposed through interfaces to different clients. Typically, an interface is exposed to a group of clients which needs to use common functionalities.

1.  interface IStore
2.  {
3.   void Read();
4.   void Write();
5.  }
6.   
7.  interface ICompress
8.  {
9.   void Compress();
10.  void Decompress();
11. }
12.  
13. public class Document : IStore, ICompress
14. {
15.  #region IStore
16.  
17.  public void Read()
18.  {
19.  Console.WriteLine("Executing Document's Read Method for IStore");
20.  }
21.  
22.  public void Write()
23.  {
24.  Console.WriteLine("Executing Document's Write Method for IStore");
25.  }
26.  
27.  #endregion // IStore
28.  
29.  #region ICompress
30.  
31.  public void Compress()
32.  {
33.  Console.WriteLine("Executing Document's Compress Method for ICompress");
34.  }
35.  public void Decompress()
36.  {
37.  Console.WriteLine("Executing Document's Decompress Method for ICompress");
38.  }
39.  #endregion // ICompress
40. } 

Features of Interface


1.     An interface doesn't provide inheritance like a class or abstract class but it only declare members which an implementing class need to be implement.

2.     It cannot be instantiated but it can be referenced by the class object which implements it. Also, Interface reference works just like object reference and behave like as object.

1.  IStore IObjStore = new Document();
2.  ICompress IObjCompress = new Document();

3.     It contains only properties, indexers, methods, delegates and events signature.

4.     It cannot contains constants members, constructors, instance variables, destructors, static members or nested interfaces.

5.     Members of an interface cannot have any access modifiers even public.

6.     Implicitly, every member of an interface is public and abstract. Also, you are not allowed to specify the members of an interface public and abstract or virtual.

7.     An interface can be inherited from one or more interfaces.

8.     An interface can extend another interface.

9.     A class or struct can implements more than one interfaces.

10.  A class that implements an interface can mark any method of the interface as virtual and this method can be overridden by derived classes.

11.  Implementing multiple interfaces by a class, sometimes result in a conflict between member signatures. You can resolve such conflicts by explicitly implementing an interface member.

1.  interface IStore
2.  {
3.   void Read();
4.   void Write();
5.  }
6.   
7.  interface ICompress
8.  {
9.   void Compress();
10. void Decompress();
11.}
12. 
13.public class Document : IStore, ICompress
14.{
15. #region IStore Explicit Implementation
16. 
17. public void IStore.Read()
18. {
19. Console.WriteLine("Executing Document's Read Method for IStore");
20. }
21. 
22. public void IStore.Write()
23. {
24. Console.WriteLine("Executing Document's Write Method for IStore");
25. }
26. 
27. #endregion // IStore
28. 
29. #region ICompress Implicit Implementation
30. 
31. public void Compress()
32. {
33. Console.WriteLine("Executing Document's Compress Method for ICompress");
34. }
35. public void Decompress()
36. {
37. Console.WriteLine("Executing Document's Decompress Method for ICompress");
38. }
39. #endregion // ICompress
40.}

12.  It is a good practice to start all interface names with a capital “I” letter.

Common design guidelines for Interface


1.     Keep your interfaces focused on the problem you are trying to solve and keep related tasks (methods) into a interface. Interfaces that have multiple unrelated tasks tend to be very difficult to implement in a class. Split up interfaces that contain unrelated functionality.

2.     Make sure your interface does not contain too many methods. Since too many methods makes implementing the interface difficult as the implementing class has to implement each and every method in the interface.

3.     Don't make interfaces for specific functionality. An interface should define the common functionality that can be implemented by the classes of different modules or subsystems.

When to use


1.     Need to provide common functionality to unrelated classes.

2.     Need to group objects based on common behaviors.

3.     Need to introduce polymorphic behavior to classes since a class can implements more than one interfaces.

4.     Need to provide more abstract view to a model which is unchangeable.

5.     Need to create loosely coupled components, easily maintainable and pluggable components (like log4net framework for logging) because implementation of an interface is separated from itself.

Disadvantage of Interface


1.     The main issue with an interface is that when you add a new members to its, then you must implement those members within all of the classes which implement that interface.

2.     Interfaces are slow as these required extra in-direction to find corresponding method in in the actual class.

 


1.What is an Interface ?
Interface is a contract which guarantees  client(consumer) how your classes or structs are going to behave.They consists only method skeleton and no implementations.
example-
Interface i1
{
    void Method1();
}

2.Whats the naming convention of interface ?
     The interface name should start with an I.Example--IDisposable,IEnumerable  
 
3.Whats the use of Interface?
->Interface  can be used when you cannot inherit from a class like for structs.
->More than one interface can be inherited thus supporting multiple inheritance in .Net
->Interface helps in defining a common functionality across multiple types.
->Used in plug-n-play architecture. 

4.Why Interface methods cannot have access modifiers ? 
Interface methods are always public by default.
 
5.Can Interface have properties in them ?
 yes.a property in interface is defined as below
Interface I1
{
   int prop
   {
      get;
      set;
    }
}
get and set cannot have any body.
6.Can interface have fields ?
 No

7.Can you create instance of an interface?
No you cannot create an instance of interface.

8.why is it better to access interface through interface reference only ?
9.Give a real world example of Interface ? 

10.Whats the difference between Interface and Abstract Class ?
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
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
An interface cannot have access modifiers for the subs, functions, properties etc. everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from an IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
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.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
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.
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constraints defined

11.When should we Abstract Class and Interface?     1.  If multiple versions of the component are being created and they are reused  then  use Abstract Class as they simplify versioning.By updating base class all the
derived  classes gets updated. Whearas if a new version of interface is required it
has to be created from scratch.
2. If the functionality is used across wide range then use Interface. Abstract Classes should be used for closely related objects.
3. Use interface if there are atleast 2 diff implementations available.
4. If you want to provide common functionality among all the implemented classes go for abstract classes.
12.what is explicit implementation. when is it used?
When a class which has inherited a interface explicitly implements methods of         
that  class is called explicit implementation.This method can now be accessed
only through interface instance.They are useful in cases when a class inherits
two interfaces and both of  them have same method name.
      Example --
        interface ISimpleCalculator
        {
            void Add();
        }
        interface IComplexCalculator
        {
            void Add();
        }
        class Calculator: ISimpleCalculator,IComplexCalculator
        {
            //This is explicit implementation
            void ISimpleCalculator.Add()
            {
                //doSomething
            }
            void IComplexCalculator.Add() 
           {
                //doSomething
            }
        }

Accesing these interface--

           Calculator obj = new Calculator();
            ISimpleCalculator i1 = new Calculator();
            i1.Add(); //will call ISimpleCalculator.Add()

You cannot access interface methods from class reference.
             obj.Add()  //will give compilation error.


13.Why public modifier not used in explicit implementation? 
The methods which are explicitly implemented are tied to a interface. and it can be 
accessed  only through interface reference.

14.What is implicit implementation ?  
interface ISimpleCalculator
        {
            void Add();
        }      

        class Calculator: ISimpleCalculator
        {
            //This is implicit implementation
            public void Add()
            {
                //doSomething
            }          
        }

       Add() can be access be directly class reference

15.Does structure support Inheriting from an interface ?

Yes

16.When a class A inherits from an interface I1 and another class B what should  be taken care of ?

      The class being inherited should be the base class
     example- This is how it should  be inherited
            Class A:Class B,I1   

            {

            }


       This is wrong

           Class A:I1,Class B

           {

           }


17.Can a method derived from interface marked as virtual ? 
Yes and they can then be overridden

18.Why cannot you have static method in Interface? 
Because Interface methods have implementation and also can be overriden . Thera is no point in having  static methods as they should have a body and cannot be overriden.

19.Can Interface inherit another interface ?

 Yes

20.Can Interface inherit another class ? 
Interface cannot inherit another class.

21.Can Interface have access modifier ? 
 Yes.

22.Mention some Interface in .Net Framework?
IDisposable,IEnumerable,ICollection
 

No comments:

Post a Comment