© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
4 replies
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Calling static method of interface via it's type
C#CC# / help
16mo ago
✅ Is it possible to convert a generic interface to a generic interface?
C#CC# / help
3y ago
How to pass a Type to a method for a return of the same type
C#CC# / help
3y ago
✅ Is it possible to lock method by id?
C#CC# / help
3y ago