Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading