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:
// This works
IPerson person = new Person();
person.GetName();
But:
// Doesn't works
Person person = new Person();
person.GetName();
If you want to call the default interface method from within your class then you'll need to cast this
to an IPerson
in order to do so:
private string SomeMethod()
{
IPerson self = this;
return self.GetName();
}
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.
abstract class PersonBase
{
public virtual string GetName()
{
return "Jonny";
}
}
is casting something you can use in your situation?
using System;
namespace DefaultInterfaceTest
{
class Program
{
static void Main(string[] args)
{
IPerson person = new Person();
Person fooPerson = (Person) person;
Console.WriteLine(person.GetName());
Console.WriteLine(fooPerson.Foo());
}
}
public interface IPerson
{
public string GetName()
{
return "Jonny";
}
}
public class Person: IPerson
{
public string Foo()
{
return "Hello";
}
}
}
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