Interface in C# + abstract in C#

Interface always starts with I . It is the naming convention.

 

In a more basic way to explain: An interface is sort of like an empty muffin pan. It’s a class file with a set of method definitions that have no code.

An abstract class is the same thing, but not all functions need to be empty. Some can have code. It’s not strictly empty.

Why differentiate: There’s not much practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there’s no code. Especially if you’re working with Java programmers who are accustomed to the term.

shareimprove this answer

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IEnumerable
{
    interface ICustomer
    {
        //interface cannot have definition
        //they only need declaration
        //it is public by default so don't put public infront of this
        //int ID; //also give the compiler error


        void Print();

        // Console.WriteLine("Hello");

    }

    class Customer : ICustomer
    {
        public void Print()
        {
            Console.WriteLine("Interface Print Method");
        }
        
    }

    class Program
    {
        static void Main(string[] args)
        {
            Customer c1=new Customer();
            c1.Print();
            Console.ReadKey();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IEnumerable
{
    interface ICustomer
    {
        //interface cannot have definition
        //they only need declaration
        //it is public by default so don't put public infront of this
        //int ID; //also give the compiler error


        void Print();

        // Console.WriteLine("Hello");

    }

    interface I2:ICustomer
    {
        void I2method();
    }


    public class Customer : I2 //but multiple interface inheritance is possible
    {
        public void Print()
        {
            Console.WriteLine("Interface1 Print Method");
        }

        public void I2method()
        {
            Console.WriteLine("I2 method");
        }
    }

    class Sample
    {
        
    }

    public class Program:Customer //,Sample  //multiple class inheritance is not possible
    {
        static void Main(string[] args)
        {
            Customer c1=new Customer();
            ICustomer cust=new Customer();
            
            c1.Print();
            c1.I2method();
            cust.Print();
            Console.ReadKey();
        }
    }
}

Explicit Interface Implementation:

 

Interface vs Abstract

 

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.