Last active
September 17, 2021 14:47
-
-
Save Korporal/7b21244cfb8d29c6335ff0ab567e4928 to your computer and use it in GitHub Desktop.
Generics challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace HolidayAPI | |
{ | |
public class Schedule<T> where T : ISchedulable<IComparable> | |
{ | |
private List<T> values = new List<T>(); | |
public void AddEvent(in T Event) | |
{ | |
values.Add(Event); | |
values = values.OrderBy(r => r).ToList(); | |
} | |
public Schedule<T> ApplyHoliday(Holiday Holiday) | |
{ | |
return this; | |
} | |
public Schedule() | |
{ | |
} | |
} | |
public interface ISchedulable<out T> where T : IComparable | |
{ | |
T Value { get; } | |
} | |
public class DueDate : ISchedulable<Version> | |
{ | |
public Version Value => throw new NotImplementedException(); | |
} | |
} | |
namespace HolidayAPITests | |
{ | |
[TestClass] | |
public class ScheduleTests | |
{ | |
[TestMethod] | |
public void TestCreate1() | |
{ | |
var schedule = new Schedule<DueDate>(); | |
} | |
} | |
} |
Reformatted into a SharpLab which compiles
And working: SharpLab. Variance only works for reference types (for obvious reasons, when you stop and think about it), so we need to introduce that DateTime
as its own generic type parameter.
I'd question the overall design, though...
@canton7 - I see, thanks. I had found that solution (I should have mentioned) and wanted to avoid the caller of the constructor having to kmow about the type used to implement DueDate, I want that detail to be an implementation detail. Is there any way?
When we use a ref type it works fine but a value type seems to be fundamentally upsetting it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Problem Statement:
Get the test method to compile when we replace type
Version
(a class) withDateTime
(a struct) in the classDueDate
above.