Home > DeveloperSection > Articles > Interfaces

Interfaces


.NET .NET 
Ratings:
0 Comment(s)
 5128  View(s)
Rate this:

Interfaces in C#.Net

An interface looks like a class, but has no implementation. The only thing it contains is definitions of events, indexers, methods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined.

Example

//defining first interface

    interface Ifirst

    {

        void sum(int a, int b);

    }

 

//defining second interface which inherits first interface

    interface Isecond:Ifirst

    {

        void sub(int a, int b);

    }

 

//defining class which inherits second interface

 

    class newClass : Isecond

    {

//implementing interface defined methods

        public void sum(int a, int b)

        {

            MessageBox.Show("Sum is: " + (a + b).ToString());

        }

        public void sub(int a, int b)

        {

            MessageBox.Show("Difference is: " + (a - b).ToString());

        }

    }

Demonstrating use

//creating instance of class

newClass c = new newClass();

private void btnSum_Click(object sender, EventArgs e)

        {      

//calling sum() of Ifirst interface    

c.sum(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text));

        }

 

 

 

 

        private void btnSub_Click(object sender, EventArgs e)

        {

//calling sub() of Isecond interface

c.sub(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text));

        }


Don't want to miss updates? Please click the below button!

Follow MindStick