Reputation: 21657
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");
}
public class CTest : ITest
{
public void Print(string message)
{
Console.WriteLine(message);
}
}
I have an implementation that is only for this interface.
So, in this case, does my interface contains a method or not?
Upvotes: 2
Views: 2008
Reputation: 62308
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
.
Upvotes: 1
Reputation: 767
In Your case You implemented Extension method that can be used only on types declared as ITest. ITest Interface does not contain method FullPrint. You can define you base class andimplement interface:
public class Test : ITest
{
public void Print(string message)
{
// implementation
}
}
Then, You can use that method in the following way:
ITest variable = new Test();
variable.FullPrint("Hello");
Upvotes: 1
Reputation: 157136
You have declared a method (giving its signature), but you didn't give it an implementation. Interfaces can't hold implementations, base classes can.
In your case it would mean you have to rewrite to:
public /*abstract */ class TestBase
{
public virtual void Print(string message)
{
// implementation
}
}
Upvotes: 1