As I know I cannot create a concrete method in an interface in c# it should give me an error but when I Do That
interface IPerson
{
void x();
public void y()
{
Console.WriteLine("Welcome From Interface");
}
}
class Teacher : IPerson
{
public void x()
{
}
}
And in the main
static void Main(string[] args)
{
IPerson p = new Teacher();
p.y();
Console.ReadKey();
}
the output became => Welcome From Interface Why it did not give me an error?
This feature is new in C# 8 and is called Default implementations in interfaces.
Basically you can provide an implementation of a method inside an interface that gets "inherited" by the class that implements it.
Note that the default implementation can only access other members in the interface, and you cannot declare state other than that the interface has properties. A typical usecase is when you provide overloads that all end up chaining into one common overload, perhaps the one with the most parameters.
This makes it easier to implement an interface, but it also makes it possible to tuck on more members in an interface, without having to recompile the assemblies providing types that implement them and without having to add those methods to those types.
Note that the class that implements the interface can still implement the member. You will then have that implementation instead. Note that this is not inheritance, so you cannot call base.y()
from your method that is implemented in the class, to call the default implementation in the interface. The default implementation is used, unless you provide an actual implementation in the class, then that implementation completely replaces the default implementation from the interface.
Another detail is that the methods are only available you have a variable of the interface type, not of the concrete type.
So while this works:
IPerson p = new Person();
p.y();
this doesn't:
var p = new Person(); // p is now of type Person
p.y(); // CS1061 'Type' does not contain a definition for 'y' and no accessible extension method 'y' could be found
Since you already have a very good and short example in your question I won't add more code here, unless you ask for clarifications on some other details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With