C
C#2y 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;
}
}
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
3 Replies
phaseshift
phaseshift2y ago
Use an as cast instead of the final cast. You'll need an extra null check Or use the as cast first
sibber
sibber2y ago
or Value is TValue tValue
Hugh
HughOP2y ago
Thanks
Want results from more Discord servers?
Add your server