C#C
C#3y ago
Hugh

✅ Casting from one generic type to another

Hi,

I've got the following:

public abstract class MyBase
{
  public abstract bool TryGetValue<TResult>(out TResult result);
}

public class MyGeneric<T> : MyBase
{
  private T _value;

  public override bool TryGetValue<TResult>(out TResult result) where TValue : default
  {
    if(typeof(TResult) != typeof(T))
    {
      result = default;
      return false;
    }

    return (TResult)Value;
  }
}


However, it's telling me that I can't do this as it can't cast Value to TValue.
How would I go about getting it to allow this, as I specifically only want to get to that point in the code if they are of the same type.

The reason for doing it like this is because I need to keep a reference to the base class elsewhere where I don't know the type.

Thanks
Was this page helpful?