Page Stats
Visitor: 219
C#.Net Interface
C# interface contains only the declaration of the methods, properties, and events, but not the implementation, it is the responsibility of the class that implements the interface and define all the members of the interface. Interfaces are declared in a same way as class declaration, but a few differences:
- Interface is declared with the keyword interface.
- Interface can't be instantiated as a class.
- Interface can't contain any code that implements its member.
- An Interface cannot include private members.
- An Interface cannot be abstract and sealed as a class.
A class can support multiple interfaces and multiple classes can support the same interface. If a class implements an interface it has to define all its members otherwise class has to be declared as abstract.
Syntax: Interface declaration
interface IMyInterface { // interface members1; // interface members2; }
Interface inheritance is also possible like class inheritance.
Example 1: Implements a interface in a class.
interface circle { float area(float r); } class example : circle { public float area(float r) { float a = 3.14f * r * r; return a; } } class Program { static void Main(string[] args) { example ex = new example(); circle cir=ex; float f = cir.area(5.0f); Console.WriteLine(f); Console.Read(); } }
Example 2: To implements multiple interfaces
interface ICircle { float circle(float r); //abstract method declaration to find area of circle }
interface IRectangle { int rectangle(int l, int b); //abstract method declaration to find area of rectangle }
class Area : ICircle, IRectangle { public float circle(float r) //define { float a = 3.14f * r * r; return a; } public int rectangle(int l, int b) { int a = l * b; return a; } }
class Program { static void Main(string[] args) { Area obj = new Area(); ICircle cir = obj; //float a = obj.area(5.5f); float a = cir.circle(5.5f); Console.WriteLine("Area of circle = " + a); IRectangle rec = obj; int a2 = rec.rectangle(10, 20); Console.WriteLine("Area of rectangle = " + a2); Console.Read(); } }