C
C#5mo ago
Evyr

Is it possible to change the return type of interface method to the type of the implementing struct?

Say I have the following code:
interface IBiggerThan
{
public abstract IBiggerThan GetBiggest(IBiggerThan compareTo);
}
struct A : IBiggerThan
{
float _a;
public A GetBiggest(A compareTo)
{
if (this._a > compareTo._a)
return this;
return compareTo;
}
}
struct B : IBiggerThan
{
float _b;
public B GetBiggest(B compareTo)
{
if (this._b > compareTo._b)
return this;
return compareTo;
}
}
interface IBiggerThan
{
public abstract IBiggerThan GetBiggest(IBiggerThan compareTo);
}
struct A : IBiggerThan
{
float _a;
public A GetBiggest(A compareTo)
{
if (this._a > compareTo._a)
return this;
return compareTo;
}
}
struct B : IBiggerThan
{
float _b;
public B GetBiggest(B compareTo)
{
if (this._b > compareTo._b)
return this;
return compareTo;
}
}
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
Sossenbinder
Sossenbinder5mo ago
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.
Evyr
EvyrOP5mo ago
I think so, thanks turns out I went down a similar line to this about 30 minutes ago but misused generics and threw errors
Sossenbinder
Sossenbinder5mo ago
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
Want results from more Discord servers?
Add your server