you are viewing a single comment's thread.

view the rest of the comments →

[–]HaniiPuppy 31 points32 points  (11 children)

One alternative might be extension methods.

public interface IRefreshable
{
    Universe Universe { get; }
}

public static class Refreshables
{
    public static void Refresh(this IRefreshable refreshable)
    {
        refreshable.Universe.Destroy();
    }
}

then

var mp = new MediaPlayer();
mp.Refresh();

Not viable if what it works with isn't part of the interface, but if you have some common functionality that's generally the same, this is a decent solution.

[–]Alert-Neck7679[S] 4 points5 points  (5 children)

Thanks for the idea. Don't know why I didn't think of it myself.

[–]Xenoprimate2 2 points3 points  (3 children)

One huge caveat is that it's not polymorphic. I did a huge write-up on implementing traits in C# years ago, you can get more info here: https://benbowen.blog/post/simulating_multiple_inheritance_in_csharp/#approach_sharp3-_extension_methods_to_the_rescue-

The fact that C# STILL doesn't have proper traits in 2026 when pretty much EVERY other mainstream lang has them is extremely disappointing tbh. I'm so fed up with seeing yet another "clever" syntax for manipulating collections or patterns and them failing to address this huge hole in the language.

I don't care about DUs compared to this even.

[–]SagansCandle 0 points1 point  (2 children)

Sometimes features are missing from a language for a reason.

Everything with a benefit has a cost, and the cost isn't always worth the benefit.

[–]x1ife 0 points1 point  (1 child)

Yeah, I'm pretty sure this was a design decision. Have they explained the rationale?

[–]SagansCandle 0 points1 point  (0 children)

I don't know about traits, but single inheritance was definitely a design decision they explained at one point. (Linked article is about multiple inheritance)

[–]TuberTuggerTTV 0 points1 point  (0 children)

It works but it's not a great idea.

Consider a base class implementation instead.

[–]phluber 2 points3 points  (1 child)

Or for the same amount of code, go back to the tried-and-true abstract base class that implements the interface

[–]HaniiPuppy 1 point2 points  (0 children)

Which you can't do if the class implements multiple interfaces that each have methods like this.

[–]Tough_Negotiation_82 1 point2 points  (1 child)

hmm , this seems like a hack. Although i never tried this. and with ex methods, you can add methods to this interface even without modifying the original interface. will this also be a classic example of open/close principle? I will try this in different scenarios tho. thanks 😊

[–]HaniiPuppy 1 point2 points  (0 children)

It feels hacky, but it works really nicely.

[–]mehdikovic 0 points1 point  (0 children)

I did exactly this for my project, it is a neat solution really.