How to make a class and a record share the same method in C#?

I have a legacy class ExampleClass and its successor, a record ExampleRecord.
Both implement the interface IExample that requires a method ExampleMethod.

Is it possible to have both the class and the record use the same method codevise?
If yes, how?

>Solution :

Option #1: Extension methods: Add the common method as an extension method to the interface. This way, it belongs neither to the class, nor to record, and instead it is free-floating; any code that has access to the interface should also be given access to the extension method.

Option #2: Default interface methods: Upgrade to C# language version 8.0 or above and then make the common method a Default Interface Method. (See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods) This makes things even simpler: any code that has access to either the class or the record automatically has access to the default interface method.

Of course these approaches will only work if the method relies exclusively on functionality offered by that interface and nothing else.

Leave a Reply