Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Interface with method that returns an implementation of multiple interfaces

Tags:

c#

interface

When working with interfaces, I frequently run into the case where I want to ensure that a return value from a property or method, or sometimes a parameter to a method, implements TWO or more interfaces without creating a new interface.

My specific instance right now is that I want to specify that a method will result in a IEnumerable<SomeType> that also supports INotifyCollectionChanged - that way another object using the interface does not have to typecast and can still access both settings. (I don't want to use ReadOnlyObservableCollection explicitly because it only works well with ObservableCollection objects, but I would also like to leave the option open for future implementers of the interface to use it if they want to.)

I'm thinking that this can only be handled with parameters to a method, not return values, by providing a method declaration as follows:

void SetStringData<T>(T data) where T : IEnumerable<string>, INotifyCollectionChanged

Just to be clear, what I'd really like is something where the using class CAN'T specify the exact return type. Similar to the following, but obviously the syntax doesn't work or even make sense.

(IEnumerable<string>, INotifyCollectionChanged) GetStringData()

Any suggestions on how I can do this? Or, failing that, how I can achieve the same results?

like image 576
Matt DeKrey Avatar asked Mar 05 '26 04:03

Matt DeKrey


1 Answers

The only way I can see this being done is making use of of dynamic as its all resolved at runtime, e.g.:

public dynamic GetStringData()
{

}

And:

IDisposable disposable = GetStringData();
ISomeOtherInterface other = GetStringData();

BUT you lose all type safety that the compiler would fall over on. I think the best way to do this is to make a composite interface.

public IComposite GetStringData()
{

}

And:

IEnumerable<string> enumerable = GetStringData();
like image 80
Matthew Abbott Avatar answered Mar 07 '26 18:03

Matthew Abbott