Skip to content

Instantly share code, notes, and snippets.

@Korporal
Last active September 17, 2021 14:47
Show Gist options
  • Save Korporal/7b21244cfb8d29c6335ff0ab567e4928 to your computer and use it in GitHub Desktop.
Save Korporal/7b21244cfb8d29c6335ff0ab567e4928 to your computer and use it in GitHub Desktop.
Generics challenge
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>();
}
}
}
@canton7
Copy link

canton7 commented Sep 17, 2021

Reformatted into a SharpLab which compiles

@canton7
Copy link

canton7 commented Sep 17, 2021

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...

@Korporal
Copy link
Author

Korporal commented Sep 17, 2021

@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