Interface inherits another interface – C Sharp example

Interface inherits another interface C# example- An interface can inherit another interface or other multiple interfaces in C# programs.

In interface example below, the interface B is inheriting another interface A.

interface A {
	void fa();
}
 
interface B : A {
	void fb();
}

If a class is implementing the interface B, then the class must implement methods from both the interface B and A.

Example of an interface inherits another interface

/*
 * Interface inherits another interface C# example
 */
 
interface A {
	void fa();
}
 
interface B : A {
	void fb();
}
 
// Class will implement methods from both interfaces
// As interface B is also inherits interface A
class XYZ : B {
 
	
	public void fa() {
		Console.WriteLine("XYZ:fa");
	}
 
	
	public void fb() {
		Console.WriteLine("XYZ:fb");
	}
 
}
 
/*
 * Test
 */
public class Sample {
 
	public static void Main(String[] args) {
 
		XYZ obj = new XYZ();
		obj.fa();
		obj.fb();
 
	}
 
}

Output:

XYZ:fa
XYZ:fb

Example of Interface inheriting multiple interface

In fact, an interface can inherit multiple interfaces like below.

interface A {
	void fa();
}
interface C {
	void fc();
}
 
interface B : A,C {
	void fb();
}

C# code:

Class XYZ will implement methods of every interfaces, even though class is implementing the interface B only.

  /*
 * Interface extends multiple interfaces C# example
 */
 
interface A {
	void fa();
}
interface C {
	void fc();
}
 
interface B : A,C {
	void fb();
}
 
 
// Class will implement methods from all interfaces
// As interface B is also inherits interface A and C
class XYZ : B {
 
	
	public void fa() {
        Console.WriteLine("XYZ:fa");
	}
 
	
	public void fb() {
        Console.WriteLine("XYZ:fb");
	}
 
	
	public void fc() {
        Console.WriteLine("XYZ:fc");
		
	}
 
}
 
/*
 * Test
 */
public class Sample {
 
	public static void Main(String[] args) {
 
		XYZ obj = new XYZ();
		obj.fa();
		obj.fb();
		obj.fc();
 
	}
 
}

Output:
XYZ:fa
XYZ:fb
XYZ:fc

Related Posts