Reputation: 2617
Given the following interface
with a default implementation:
public interface IState
{
string Name => "Unknown";
}
And a concrete implementation as follows:
public class Demo: IState
{
public void PrintName()
{
Console.WriteLine(this.Name); // <-- this is invalid syntax
}
}
Is it possible to call the default implementation from within the concrete type?
I've had a look through the documentation for default implementations for C# 8.0 and if the answer is there I cannot spot it.
Upvotes: 5
Views: 317
Reputation: 1500275
You can use it by casting this
to the interface, and call the property on the result of the cast. It's as if the class implemented the property using explicit interface implementation. Here's a complete example that prints "Unknown":
using System;
public interface IState
{
string Name => "Unknown";
}
public class Demo : IState
{
public void PrintName()
{
Console.WriteLine(((IState) this).Name);
}
}
class Program
{
static void Main()
{
new Demo().PrintName();
}
}
Upvotes: 7