|
An interface looks like a class, but has no implementation. An interface is a C# reference type with members that do not have implementations. Interfaces only have method signatures. The following are the properties of the interfaces:-
- It contains 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.
- Interfaces are like protocol or standard that needs to be maintained by the classes or structs that are implementing that interface.
- We can have final variables and abstract methods in interface. This means the classes or structs that are implementing interfaces need to provide the body for all the methods that are there in interfaces.
- No need to provide the access specifier for method that is there in interface, all the methods are public.
- We have the concept of inheritance in interface. One interface can extends another interface.
Syntax:
Interface InterfaceName {
// method signature
}
Class implementing the Interfaces.
Class clsTest: ITestInterface
{
// method defined here
}
Structs Implementing Interface.
struct strTest: IstructsInterface
{
// method defined here
}
Interfaces may inherit other interfaces.
Example: Demonstrate Interfaces

ClsInterface12.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace cSHARPEXAMPLES
{
interface IParentInterace
{
String display();
}
interface IChildInterface : IParentInterace
{
String Show();
}
class ClsInterface12 : IChildInterface
{
String str = "Hi" ;
public ClsInterface12( String pStr) {
str = pStr;
}
public String Test() {
return str;
}
public String display()
{
return str + " : Display Of Base Interface" ;
}
public String Show()
{
return str + " : Show Of Child Interface" ;
}
}
}
Form12.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace cSHARPEXAMPLES
{
public partial class Form12 : Form
{
public Form12()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
ClsInterface12 obj = new ClsInterface12 ( "Hello" );
label1.Text = obj.Test();
label2.Text = obj.display();
label3.Text = obj.Show();
}
private void Form12_Load( object sender, EventArgs e)
{
label1.Text = "" ;
label2.Text = "" ;
label3.Text = "" ;
}
}
}
Output:
Click On: Interface Executed Button
.jpg)
|