I have a situation where I need to require that a variable is of a certain type, but that it also implements a specific custom interface. Specifically, I want to require that the object be a FrameworkElement, but that it also implement a custom interface, call it IExample.
Is there any way I can do this from either the declaration of IExample or the actual variable? I'm envisioning something like this (pseudo syntax):
public FrameworkElement<IExample> ChildView { get; set; }
Either that or I want to declare it as a constraint on the interface itself:
public interface IExample : FrameworkElement
Are either of these possible in C#? Are there alternatives that can accomplish the same thing? Basically I just want to require that instances be of a subclass of FrameworkElement that also implements IExample.
You could use a generics constraint at the class level and then apply it to the property as properties themselves cannot directly define constraints.
public class SomeClass<T> where T : FrameworkElement, IExample {
public T ChildView { get; set; }
}
Or on an interface
public interface ISomeInterface<T> where T : FrameworkElement, IExample {
T ChildView { get; set; }
}
Or at the method level if you want to take a type in as a parameter that conforms to both being of type FrameworkElement and also implementing IExample
public void SomeMethod<T>(T someParameter) where T : FrameworkElement, IExample
{ /*do something with instance someParameter*/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With