1

I have a generic version of an interval with start and end, and a concrete class that uses DateTime.

The generic version defines an Empty value for convenience. The problem comes when I run the this code.

It complaints in the only line of the Main method:

Unable to cast object of type 'Interval`1[System.DateTime]' to type 'DateTimeInterval'.

It complaints that an instance cannot be converted to my desired type. Why?? I can't understand this restriction.

void Main()
{
    DateTimeInterval p = (DateTimeInterval)DateTimeInterval.Empty;
}

class Interval<T>
{
    public Interval(T start, T end)
    {       
        Start = start;
        End = end;
    }
    
    public T Start { get; set; }
    public T End { get; set; }
    
    public static Interval<T> Empty = new Interval<T>(default, default);
}

class DateTimeInterval : Interval<DateTime> 
{
    public DateTimeInterval(DateTime start, DateTime end):base(start, end)
    {       
    }   
}
SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • 2
    Can you show the litteral error? – Stefan Jul 06 '20 at 12:18
  • Does this answer your question? [C# variance problem: Assigning List as List](https://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase) –  Jul 06 '20 at 12:22
  • @Stefan Unable to cast object of type 'Interval`1[System.DateTime]' to type 'DateTimeInterval'. – SuperJMN Jul 06 '20 at 12:22
  • Also: https://stackoverflow.com/questions/58592905/c-sharp-downcasting-generic-object-with-derived-interfaces-to-the-base-interfa/58593377#58593377 & https://stackoverflow.com/questions/58133125/create-a-generic-collection-of-derived-interfaces-from-a-collection-of-base-inte/58133434#58133434 & https://www.c-sharpcorner.com/uploadfile/scottlysle/downcasting-in-C-Sharp/ & https://www.c-sharpcorner.com/blogs/upcast-and-downcast-basics –  Jul 06 '20 at 12:22
  • @OlivierRogier I'm not using lists. I don't see the same issue here. – SuperJMN Jul 06 '20 at 12:25
  • @SuperJMN The theory remains the same whatever types. –  Jul 06 '20 at 12:26
  • Also: https://stackoverflow.com/questions/12565736/convert-base-class-to-derived-class & https://stackoverflow.com/questions/729527/is-it-possible-to-assign-a-base-class-object-to-a-derived-class-reference-with-a –  Jul 06 '20 at 12:34

1 Answers1

3

This issue has nothing to do with variance and generics. Next code will give you the same error:

class Interval1
{
    public static Interval1 Empty = new Interval1();
}

class DateTimeInterval1 : Interval1
{
}

DateTimeInterval1 p = (DateTimeInterval1)DateTimeInterval1.Empty;

Reason being that Empty is instance of Interval not DateTimeInterval, so it can't be cast to DateTimeInterval.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132