I have this peace of code in a console app .net core 3.1 on VS 16.5.1:
namespace DefaultInterfaceTest
{
class Program
{
static void Main(string[] args)
{
var person = new Person();
person.GetName();//error here
}
}
public interface IPerson
{
string GetName()
{
return "Jonny";
}
}
public class Person: IPerson
{
}
}
I was hopping I could access the default implementation oif GetName from the person itself, as it's a public method but it yields this error:
'Person' does not contain a definition for 'GetName' and no accessible extension method 'GetName' accepting a first argument of type 'Person' could be found (are you missing a using directive or an assembly reference?)
How can I access the default implementation of an interface from outside code or from the Person class itself? Thanks!
You can only access default implementation methods by calling via an interface reference (think of them as explicitly implemented methods).
For example:
But:
If you want to call the default interface method from within your class then you'll need to cast
this
to anIPerson
in order to do so:There's no way around the case if you are using interfaces. If you really want this sort of behavior then you'll need to use an abstract class where
GetName
is a virtual method.