Is it possible to define an interface in C# which has a default implementation? (so that we can define a class implementing that interface without implementing that particular default method).
I know extension methods (as explained in this link for example). But that is not my answer because having a method extension like the following, the compiler still complains about implementing MyMethod in MyClass:
public interface IMyInterface
{
string MyMethod();
}
public static class IMyInterfaceExtens
{
public static string MyMethod(this IMyInterface someObj)
{
return "Default method!";
}
}
public class MyClass: IMyInterface
{
// I want to have a default implementation of "MyMethod"
// so that I can skip implementing it here
}
I am asking this because (at least as far as I understand) it is possible to do so in Java (see here).
PS: having an abstract base class with some method is also not my answer simply because we don't have multiple inheritance in C# and it is different from having a default implementation for interfaces (if possible!).
As a newbe C# programmer I was reading through this topic and wondered if the following code example could be of any help (I don't even know if this is the proper way to do it). For me it allows me to code default behavior behind an interface. Note that I used the generic type specifiction to define an (abstract) class.
Short Answer:
No, you cannot write implementation of method in interfaces.
Description:
Interfaces are just like contract ,so that the types that will inherit from it will have to define implementation, if you have a scenario you need a method with default implementation, then you can make your class abstract and define default implementation for method which you want.
For Example:
and now in Dervied class:
UPDATE (C# 8 will have support for this):
C# 8 will allow to have default implementation in interfaces
I develop games so I often want to have common function for all implementations of an interface but at the same time allow each implementation to do its own thing as well, much like a subclass' virtual / override methods would function.
This is how I do it:
C# v8 will start allowing concrete method implementation in interfaces as well. This will allow your concrete implementation classes to not break when you change the interfaces being implemented in future.
So something like this will be possible in the next language version:
Please refer to this GitHub issue # 288. Also Mads Torgersen talks about this upcoming feature at length in this channel 9 video.
Note: Current version of C# language in RTM state is v7 at the time of writing this answer.
Not directly, but you can define an extension method for an interface, and then implement it something like this
Edit* It is important that the extension method and the method that you are implementing are named differently, otherwise you will likely get a stackoverflow.