© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
4 replies
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
Value
to
TValue
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Type Casting
C#CC# / help
4y ago
✅ Get property from generic type?
C#CC# / help
4y ago
Passing one int from one script to another
C#CC# / help
2y ago