2

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:

Michael Ziluck
  • 599
  • 6
  • 19
  • What about the answer present here: https://stackoverflow.com/a/503359/6757825 – Vivek May 20 '21 at 18:24
  • I'm confused. Why are you checking for IBaseWidget at all when you want to test if it's ALSO implementing IValueWidget, and those two interfaces are not related...? – Nikki9696 May 20 '21 at 18:35
  • `IValueWidget` implements `IValueWidget`, so what you're really asking is whether the `IValueWidget` interface is implemented, regardless of the type parameter `T` used. See duplicate...it answers exactly what you're asking. – Peter Duniho May 20 '21 at 19:28

0 Answers0