Similar to this Java question. I would like to specify that a variable implements multiple interfaces. For instance
private {IFirstInterface, ISecondInterface} _foo;
public void SetFoo({IFirstInterface, ISecondInterface} value)
{
_foo = value;
}
Requirements:
- I don’t have the ability to add an interface to most type that would be passed in to Foo. So I can’t create a third interface that inherits from IFirstInterface and ISecondInterface.
- I would like to avoid making the containing class generic if possible because the type of Foo doesn’t have much to do with the class and the user isn’t likely to know it at compile time.
- I need to use foo to access methods in both interfaces at a later time.
- I would like to do this in a compiler safe way, i.e. no trying to cast to the interface just before trying to use it. If foo does not implement both interfaces quite a bit of functionality won’t work properly.
Is this possible?
Edit: I’ve wanted this a few times for various reasons. In this instance it’s because I am changing a set of properties from ObservableCollections to ReadOnlyObservableCollections. I have a helper class that creates a projection from a source ObservableCollection to another Collection. Since ReadOnlyObservableCollection does not inherit from ObservableCollection and I only need operations in IList and INotifyCollectionChanged I was hoping to store my source collection as a combination of these two interfaces rather than requiring an ObservableCollection.
If you want to constrain your method
SetFooto take only parameters that implement these two interfaces, then you are in luck:From this point on, any time you want to access your
_foomember as one of either of these two interfaces, you’ll just have to access it via casts:(IFirstInterface)_fooor(ISecondInterface)_foo, respectively.You did say you’d like to avoid resorting to casts for compile-time safety; but I think, if you figure out a way to ensure that
_foogets initialized usingSetFooabove, you can cast all you want with peace of mind.I just realized the below describes something you specifically stated in the question you didn’t want to do. So, I say, go with the above.
Another idea would be, since it looks like this
_fooobject is a class member (I’m basing this assumption on the_in the variable name), you could define your class in this way:Whether this actually makes sense depends, obviously, on your specific scenario. You’ll definitely have to think it through, as classes with constraints like this sometimes lead to issues you might not have expected down the road (such as that
SetFoonow must take a parameter of typeT, not just any class that implements your two interfaces).