Search Forum
(57415 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

C# Interface Implementation
By Pavel Tsekov

Interface implementation can be confusing...

I see a feature in C# that can be very confusing. In the example below we have a class (Test) that implements 2 interfaces (I1 and I2). So the logic says that we should have implementations in the class Test for both MyFunction() methods from I1 and I2. BUT! As you see in the example below everything works fine with only 1 implementation. This is not as correct as we expect, because we can't be sure which of the two interfaces is implemented in the MyFunction method in class Test. So the solution is in another example (EXAMPLE2). In Example2 MyFunction() is implemented in class Test for each interface, by using a different method. (I1.MyFunction() -> for I1, I2.MyFunction() -> for I2). So now everything is clear, isn't it?

//EXAMPLE 1
using System;

namespace PavelTsekov
{
	interface I1
	{
		void MyFunction();
	}
	interface I2
	{
		void MyFunction();
	}
	class Test : I1,I2
	{
		public void MyFunction()
		{
			Console.WriteLine("Guess which interface I represent???!");
		}
	}
	class AppClass
	{
		public static void Main(string[] args)
		{
			Test t=new Test();
			I1 i1=(I1)t;
			i1.MyFunction();
			I2 i2=(I2)t;
			i2.MyFunction();
		}
	}
}

//EXAMPLE 2
using System;

namespace PavelTsekov
{
	interface I1
	{
		void MyFunction();
	}
	interface I2
	{
		void MyFunction();
	}
	class Test : I1,I2
	{
		void I1.MyFunction()
		{
			Console.WriteLine("Now I can say this here is I1 implemented!");
		}
		void I2.MyFunction()
		{
			Console.WriteLine("Now I can say this here is I2 implemented!");
		}
	}
	class AppClass
	{
		public static void Main(string[] args)
		{
			Test t=new Test();
			I1 i1=(I1)t;
			i1.MyFunction();
			I2 i2=(I2)t;
			i2.MyFunction();
		}
	}
}