I have a .Net 6.0 application in Visual Studio 2019. I'm trying to get default interface implementations working. For some reason, it doesn't seem to be recognizing the default implementations in the class definition.
Here is a sample code snippet:
public interface IFooBar
{
protected bool BoolProperty { get; set; }
protected Guid StringProperty { get; set; }
protected void SampleMethod1(string param)
{
}
protected void SampleMethod2()
{
}
}
public class FooBase
{
}
public class Foo : FooBase, IFooBar
{
protected bool IFooBar.BoolProperty { get; set; }
protected Guid IFooBar.StringProperty { get; set; }
protected SomeMethod()
{
SampleMethod1("Test String");
}
}
Here is a snippet from my Visual Studio 2019 project file:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>preview</LangVersion>
</PropertyGroup>
Here is the error message I'm seeing.
Error CS0103 The name 'SampleMethod1' does not exist in the current context
I've got two questions/issues:
Why did the compiler require me to define my interface properties as such in my concrete class: protected bool IFooBar.BoolProperty { get; set; } protected Guid IFooBar.StringProperty { get; set; }
Why is the default method implementation not recognized in my concrete class?
Problem
Interface default implementation requires explicit cast of the instance to that interface type which has the default implementations.
Fixed code
Explanation
There are two approaches to implementing interfaces: implicit and explicit.
Implicit interface implementation
The most popular approach. Interface properties are declared the same way as any others:
In this case the properties behave just like they any other property that belongs to this class:
Explicit interface implementation
The case of your
Fooclass. The syntax and behavior differ:These properties will not be visible unless you cast
FootoIFooBar:This is useful when you don't want to automatically show the properties from the interface in your class, make them a little bit hidden, accessible to users who know what they're looking for.
Conclusion
Default interface implementations use explicit approach.