using System;
/*Interface
* just like classes interfaces also contains properties, methods, delegates or events
* but only declarations and no implementations
*
* If a class or a struct inherit from an interface,
* it must provide implementation for all interface members
* otherwise we get a compiler error
*/
interface ICustomer1
{
//only have declaration
//public by default, and can't put the-access modifier
void Print1(); //can't have a definition
}
interface ICustomer2
{
void Print2();
}
//can inherite from more than one interface
class Customer : ICustomer1, ICustomer2
{
//but need to be definition on the drived class
public void Print1()
{
Console.WriteLine("Print1");
}
public void Print2()
{
Console.WriteLine("Print2");
}
}
public class Program
{
public static void Main(string[] args)
{
Customer C1 = new Customer();
C1.Print1();
C1.Print2();
//can't create an instance of an interface
//but an interface reference variable can point to a derived class object
ICustomer1 Cust = new Customer();
}
}
=====================================
Explicit
using System;
interface I1
{
void InterfaceMethod();
}
interface I2
{
void InterfaceMethod();
}
public class Program: I1, I2
{
//Explicit
public void InterfaceMethod() //making a default
//void I1.InterfaceMethod()
{
Console.WriteLine("I1 interface Method");
}
void I2.InterfaceMethod()
{
Console.WriteLine("I2 interface Method");
}
public static void Main(string[] args)
{
Program P = new Program();
//P.InterfaceMethod(); //ambigus but not error
//after using explicit, it should use type casting
((I1)P).InterfaceMethod(); // make a clear
((I2)P).InterfaceMethod();
//another way
I1 i1 = new Program();
I2 i2 = new Program();
i1.InterfaceMethod();
i2.InterfaceMethod();
//using a default
P.InterfaceMethod();
}
}
====================
multiple class inheritance using interfaces
using System;
interface IA
{
void AMethod();
}
class A : IA
{
public void AMethod()
{
Console.WriteLine("A");
}
}
interface IB
{
void BMethod();
}
class B : IB
{
public void BMethod()
{
Console.WriteLine("B");
}
}
class AB : IA, IB
{
A a = new A();
B b = new B();
public void AMethod()
{
a.AMethod();
}
public void BMethod()
{
b.BMethod();
}
}
class Program
{
public static void Main()
{
AB ab = new AB();
ab.AMethod();
ab.BMethod();
}
}