Is it possible to change the return type of interface method to the type of the implementing struct?
Say I have the following code:
I want to have GetBiggest return an instance of the struct its implemented within. This code obviously won't compile, but I'm wondering if there's a way to implement the intent behind it. I want to avoid returning object or IBiggerThan and then casting it wherever this method gets called, instead I want the return type to explicitly be that of the implementing struct. Is this possible, or am I missing something important?
3 Replies
Are you looking for the CRTP by chance?
https://blog.stephencleary.com/2022/09/modern-csharp-techniques-1-curiously-recurring-generic-pattern.html
Modern C# Techniques, Part 1: Curiously Recurring Generic Pattern
The curiously recurring generic pattern, where a base type or interface has its derived type as a generic parameter. Part of a series looking at modern C# code techniques.
I think so, thanks
turns out I went down a similar line to this about 30 minutes ago but misused generics and threw errors
Neat. I think it's a good idea in this case anyways, since with a interface-based return type you'll run into boxing behavior when working with structs