To rectify the drawback of multiple inheritance, the generator of C# have introduced a new concept called interfaces. Java programmers may be well aware of this concept. All interfaces should be declared with the keyword interface. You can implement any number of interfaces in a single derived class, but you should provide signatures to all method definitions of the corresponding interfaces. To illustrate, Example 1 shows how to declare interfaces and implement them in a class:
Example 1
using System;namespace InterfaceExample{ interface InterAritical { void Show(); }
class ClsAritical : InterAritical { public void Show() { Console.WriteLine("Show() method Implemented"); }
public static void Main(string[] args) { ClsAritical clsAritical = new ClsAritical(); clsAritical.Show(); } }}The output of this example isShow() method Implemented
Combining Interfaces:Two or more interfaces can be combined into a single interface and implemented in a class, as shown in Example 2:Example 2using System;namespace InterfaceExample{ interface InterAritical { void Show(); }
interface InterAritical1 { void Display(); }
interface CombineInterAritical : InterAritical, InterAritical1 { //Above interfaces combined }
class ClsAritical : CombineInterAritical { public void Show() { Console.WriteLine("Show() method Implemented"); }
public void Display() { Console.WriteLine("Display() method Implemented"); }
public static void Main(string[] args) { ClsAritical clsAritical = new ClsAritical(); clsAritical.Show(); clsAritical.Display(); } }}The output of the example Show() method ImplementedDisplay() method Implemented
is and as oprator in interface:
You easily can determine whether a particular interface is implemented in a class by using is and as operators. The is operator enables you to check whether one type or class is compatible with another type or class; it returns a Boolean value. Example 3 illustrates the usage of the is operator.
Example 3using System;namespace InterfaceExample{ interface InterAritical { bool Show(); }
interface InterAritical1 { bool Display(); } class ClsAritical : InterAritical { public bool Show() { Console.WriteLine("Show() method Implemented"); return true; } public static void Main(string[] args) { ClsAritical clsAritical = new ClsAritical(); clsAritical.Show(); if (clsAritical is InterAritical1) { InterAritical1 clsRefrence = (InterAritical1)clsAritical; bool ok = clsRefrence.Display(); Console.WriteLine("Method Implemented"); } else { Console.WriteLine("Method not implemented"); } } }}The output of the example is.Show() method ImplementedMethod not implemented
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18