C# Interfaces with optional methods
I understand that interfaces are contracts and any changes (even additions) break any dependent code. However, I could have sworn I read something a while back that one of the recent .NET versions (3, 3.5??) added a new attribute that could be applied to new interface members. This attribute allowed versioning and/or making members optional. It would have been something like:
interface ITest
{
void MethodOne();
[InterfaceVersion(2)]
void MethodTwo();
}
I have looked high and low for this but just can't seem to find it. I am wondering whether I simply misunderstood whatever I think I read and there is no such thing. Does someone have any insight?
Solution 1:
You should create two interfaces:
interface ITest
{
void MethodOne();
}
interface ITest2 : ITest
{
void MethodTwo();
}
This would also make it clear which functionality requires which version of your interfaces, so that you don't have to check whether the class implementing the interface is implementing just one, or both, methods.
Solution 2:
If your project fully supports C# 8.0 you can use "default interface implementations", which makes the method optional to implement and fall back on the default implementation if you choose not to implement it.
interface ITest
{
void MethodOne();
public void MethodTwo()
{
//Empty default implementation
}
}
The following SDKs support default interface implementations:
- .NET 5 and up
- .NET Core 3.0 and up
- .NET Standard 2.1 and up
- Xamarin.iOS 13.0 and up
- Xamarin.Android 10.0 and up
- Xamarin.Mac 6.0 and up
- Mono 6.0.0 and up
- Unity 2021.2 and up
This includes support for WinUI3, WPF, WinForms etc. if you run them on .NET 5 or up.
There are no plans to support default interface implementations in .NET Framework 4.8.x and earlier