Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make an existing type implement an interface?

Tags:

c#

interface

Let's say I write a really kick-ass interface. So kick-ass, in fact, that I'd like some of the builtin types I use to implement them, so that whatever code I write that uses this interface can also use the builtin types.

public interface IKickAss
{
    int Yeahhhhhhh() { get; }
}

public static class Woot
{
    public int Bar(IKickAss a, IKickAss b)
    {
        return a.Yeahhhhhhh - b.Yeahhhhhhh;
    }
}

// What I'd like to do, sort of.
public partial struct Int32 : IKickAss
{
    public int Yeahhhhhhh
    {
        get
        {
            return this;
        }
    }
}

I've wanted this many times for many reasons. The most recent is that I've implemented radix sort for "uint", but have also created a simple "IRadixSortable" interface that requires the property "uint RadixKey { get }". This means that I've basically duplicated the sorting code: once for uint arrays, the other for IRadixSortable arrays. I'd rather just write one by making the uint type implement IRadixSortable. Is there some way to do this... maybe using reflection?

Haskell can do this (i.e. typeclasses can be instantiated on any data type at any time,) and I think that's one very important reason why it's so powerful. C# could really use this feature. Maybe call it "extension interfaces" :)

like image 548
kinghajj Avatar asked Aug 31 '25 10:08

kinghajj


2 Answers

Yes and no.

You're probably looking for Duck Typing, see the following article.

like image 147
arul Avatar answered Sep 03 '25 00:09

arul


Not with interfaces, but you could do something similar using Extension Methods. You just wouldn't get the "contract"

like image 27
Tim Jarvis Avatar answered Sep 03 '25 00:09

Tim Jarvis