Buda Gavril Buda Gavril -4 years ago 187
C# Question

c#: define method in interface

I have read on msdn that:


Interfaces contain no implementation of methods.


But if I have the code:

public interface ITest
{
void Print(string message);
}

public static void FullPrint(this ITest test, string message)
{
Console.WriteLine("-------------------");
test.Print(message);
Console.WriteLine("-------------------");
}

static void Main(string[] args)
{
ITest test = new CTest();
test.FullPrint("test");
}


I have an implementation that is only for this interface.

So, in this case, does my interface contains a method or not?

Answer Source

The method FullPrint receives an instance of some type that implements ITest.

An interface, for this example the one named ITest, is essentially a contract definition. It is a promise that any types that implement that interface will contain the defined methods and properties of that interface. This is why interfaces do not have an implementation, it represents a promise/contract.

In your example again, you make a promise/contract that any type that implements ITest will contain method:

void Print(string message);

Your type (not shown) CTest implements that interface. You then create a reference of type ITest to the instance of CTest.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download