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?
protected
keywords in the class when you also have explicit interface implementations? Andprotected SomeMethod()
without a return type orvoid
? – ForgivenSampleMethod1
. You could cast the object instance to the interface to access it, but theprotected
keyword explicitly removes the method from the viable overload list so it is unavailable. If it were public in the interface, you could write this in your class:((IFooBar)this).SampleMethod1("Test String");
. – Forgivenprotected
interface methods seems to be a way to add, as you say, methods available to default implementations in interfaces that derive from the one declaring the protected method. It seems to me that the C# compiler design team hasn't seen the rule that "just because you can't doesn't mean you should". It seems to me to be an example of adding features just because they can, but not really having a clear usecase for why they should. I guess the "every feature starts with minus 100 points" rule have gone out the window. – Forgivenpublic
DIM methods, but the same technique doesn't work forprotected
. See e.g. here – CrossquestionCannot access protected member 'IFooBar.X' via a qualifier of type 'IFooBar'; the qualifier must be of type 'Foo' (or derived from it)
says something a bit different, heh. – Crossquestionvoid SampleMethod1()
, always public through the interface. But, that's just my opinion. – Forgiven