I am using the Range<T>
class described in this answer.
And I created the following sub-class in order to create a range of a specific type:
public class IntRange : Range<Int32>
{
public static List<IntRange> ParseRanges(string ranges)
{
//...
}
}
In order to finish the ParseRanges
function, I need to cast from Range<Int32>
to IntRange
. This is because I am calling a helper function I added to the Range<T>
class:
//Create a range that automatically determines the min/max between two bounds.
public static Range<T> Create(T bound1, T bound2)
{
if (bound1.CompareTo(bound2) <= 0)
{
return new Range<T>() { Minimum = bound1, Maximum = bound2 };
}
else
{
return new Range<T>() { Minimum = bound2, Maximum = bound2 };
}
}
The method calls look like the following:
IntRange range = (IntRange)Create(2, 0);
First of all, I understand that I cannot legally make this cast because it is possible for another person to create a class:
public class VerySpecialIntRange : Range<Int32> { /* ... */ }
And it isn't possible for the compiler to know if Range<Int32>
should be an IntRange
or a VerySpecialIntRange
, hence the error it spits out when I try to cast.
How can I make this cast so that I do not need to roll out the Create
function for every subclass? Sure, I have my own source code and can do this with relative ease, but if the Range<T>
is a part of some closed third-party library, and I need to subclass it, I cannot easily determine how to properly implement the Create
function.