locked
why we need the interfacce RRS feed

All replies

  • User-1780421697 posted

    An interface defines a contract which the class will comply with. The interface defines what are the operations that the class can perform.

    Actually C# do not support multiple class  inheritance so we rely n interfaces,  Most of the time we use Inversion of control , dependency injection in ASP.Net , so let suppose we have multiple implementation of a service( Db Service, Or Message Service etc) then we need a contract that keeps the class consistent, that where interface play role, on run time we can get interface object that implement any of type of service class.

     Look here for multiple examples:

    https://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp

    Monday, January 20, 2020 5:17 AM
  • User1535942433 posted

    Hi siddangoud,

    As far as I know,Interface polymorphism can call methods in different classes according to different classes. It can also complete the functions of different classes according to different classes.When the class is added, the existing interface methods can meet most of the methods in the inherited class. There is no need to redesign a set of methods for the new class, which also saves code and improves development efficiency.So,Interfaces make methods extensible.

    More details,you could refer to below codes:

    public  interface car
        {
            void total(); 
        }
        class xcar:car
        {
            public int Num { get; }
            public string Color { get; }
            public xcar(int num, string color)
            {
                Num = num;
                Color = color;
            }
            public void total()
            {
                Console.WriteLine("Yes");
            }
        }
        class runcar : car
        {
            public void total()
            {
                Console.WriteLine("No");
            }
        }
        public class Transportation
        {
            public void gettotal(car Car)
            {
                Car.total();
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
    
                Transportation t = new Transportation();
                xcar xxx = new xcar(1,"red");
                runcar yyy = new runcar();
                t.gettotal(xxx);
                t.gettotal(yyy);
                Console.ReadKey();
            }
        }

    Result:

    Best ragards,

    Yijing Sun
     

    Monday, January 20, 2020 8:45 AM