Background
My code base currently has the following interfaces and classes:
// Both DisplayValue _classes_
public class DisplayValue<T>
{
public T Value { get; set; }
}
public class DisplayValue : DisplayValue<object> {}
// Both IValueWidget _interfaces_
public interface IValueWidget<T>
{
DisplayValue<T> Value { get; set; }
}
public interface IValueWidget: IValueWidget<object>
{
new DisplayValue Value { get; set; }
}
// the BaseWidget all other widgets implement
public interface IBaseWidget
{
public string Name { get; set; }
}
The code base also has a bunch of Widgets, all of which implement IBaseWidget
. Some also implement IValueWidget
or IValueWidget<T>
, which leads me to my problem.
Problem
Say I have the following method:
public T2 DoStuff<T2>(T2 widget) where T2 : IBaseWidget
{
// this should check if the widget is the correct type
if (widget is IValueWidget)
{
}
}
In that method, I would like to have the condition work with either IValueWidget
or any generic version of IValueWidget
. I don't care whatsoever what the type of T
is, only that the given T2
can be treated as such.
Also worth mentioning, literally no types other than the ones provided above are known at compile time. Everything must work at runtime.
In Java, I could do something like this but obviously C# does not have wildcards.
public T2 DoStuff<T2 extends IBaseWidget>(T2 widget) {
if (widget instanceof IValueWidget<?>) {
}
}
Notes
As far as I can tell, this is not actually a duplicate. Please don't flag it as such if you're referring to any of these, as they are similar but definitely not the same: