An interface contains only the declaration of the methods, properties, and events, but not the implementation. It is the responsibility of the deriving class to implementation for all the members of the interface. By using Interface make easy to maintain a program. In C#, an interface can be defined using the interface keyword.

 For example, the following is a simple interface:

 For example, the following is a simple interface:

Interface Declaration:

   interface IDatabase
    {
        void Save();
        void edit(int id);
        void delete(int id);
    }

 

Now, different classes can implement IDatabase by providing an implementation of the Save(),edit(),delete() method, for example, the Product class implements IDatabase Interface And it can use Save, edit, delete method.

 

Interface implementation:

The Following fig ight click on  IDatabase and  implement interface.

 Interface in C#

public class Product : IDatabase
    {
        public void Save()
        {
            Console.WriteLine("you called Save method.");
        }
        public void edit(int id)
        {
            Console.WriteLine("you called edit method");
        }
        public void delete(int id)
        {
            Console.WriteLine("you called delete method");
        }
    }

Now, you can instantiate an object of Product class:

      static void Main(string[] args)
        {
            IDatabase pro = new Product();
            pro.Save(); // here we can save product
            pro.edit(1); // here we can pass product id as parameter for edit
            pro.delete(1);// here we can pass product id as parameter for delete
            Console.ReadLine();
        }


Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    interface IDatabase
    {
        void Save();
        void edit(int id);
        void delete(int id);
    }
    public class Product : IDatabase
    {
        public void Save()
        {
            Console.WriteLine("you called Save method.");
        }
        public void edit(int id)
        {
            Console.WriteLine("you called edit method");
        }
        public void delete(int id)
        {
            Console.WriteLine("you called delete method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            IDatabase pro = new Product();
            pro.Save(); // here we can save product
            pro.edit(1); // here we can pass product id as parameter for edit
            pro.delete(1);// here we can pass product id as parameter for delete
            Console.ReadLine();
        }
    }
}

 

Now run program and see output.

 Interface in C#

Thanks.

comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like