Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does a generic type constraint result in a no implicit reference conversion error?
    text
    copied!<p>I have created a couple of interfaces and generic classes for working with agenda appointments:</p> <pre><code>interface IAppointment&lt;T&gt; where T : IAppointmentProperties { T Properties { get; set; } } interface IAppointmentEntry&lt;T&gt; where T : IAppointment&lt;IAppointmentProperties&gt; { DateTime Date { get; set; } T Appointment { get; set; } } interface IAppointmentProperties { string Description { get; set; } } class Appointment&lt;T&gt; : IAppointment&lt;T&gt; where T : IAppointmentProperties { public T Properties { get; set; } } class AppointmentEntry&lt;T&gt; : IAppointmentEntry&lt;T&gt; where T : IAppointment&lt;IAppointmentProperties&gt; { public DateTime Date { get; set; } public T Appointment { get; set; } } class AppointmentProperties : IAppointmentProperties { public string Description { get; set; } } </code></pre> <p>I'm trying to use some constraints on the type parameters to ensure that only valid types can be specified. However, when specifying a constraint defining that <code>T</code> must implement <code>IAppointment&lt;IAppointmentProperties&gt;</code>, the compiler gives an error when using a class that is <code>Appointment&lt;AppointmentProperties&gt;</code>:</p> <pre><code>class MyAppointment : Appointment&lt;MyAppointmentProperties&gt; { } // This goes wrong: class MyAppointmentEntry : AppointmentEntry&lt;MyAppointment&gt; { } class MyAppointmentProperties : AppointmentProperties { public string ExtraInformation { get; set; } } </code></pre> <p>The error is:</p> <p><code>The type 'Example.MyAppointment' cannot be used as type parameter 'T' in the generic type or method 'Example.AppointmentEntry&lt;T&gt;'. There is no implicit reference conversion from 'Example.MyAppointment' to 'Example.IAppointment&lt;Example.IAppointmentProperties&gt;'.</code></p> <p>Could anybody explain why this does not work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload