How to distinguish Generic <T> to Generic <R>, where T is a subclass of R?
Is there a way to define an explicit converter or something similar so that the compiler can automatically populate a Generic<T> from a Generic<R> where T : R ?
The error message I get is:
The value "Link
1[Dog]" is not of type "Reference1 [Pet]" and cannot be used in this general collection.
My reference class is as follows:
public interface IReference<T> { T Value { get; } } public class Reference<T> : IReference<T> { #region Properties public string ref_type { get; set; } public string ref_id { get; set; } public Uri href { get; set; } private bool resolved = false; private T _value = default(T); public T Value { get { if( !resolved && href != null ) resolve(); else if( href == null ) return null; return _value; } } #endregion #region Constructors public Reference() { } public Reference(string ref_id) { this.ref_id = ref_id; } #endregion #region members private void resolve() { if( href != null ) { _value = APIRequestMethods.GetUri<T>(href); resolved = true; } else throw new Exception("Cannot resolve the reference because the href property has not been set."); } #endregion } +2
1 answer
This will only work if your generic type is an interface and you make your covariance type a generic type, i.e. IGeneric<out T> .
Please note that this will only work for interfaces or delegates. See Covariance and contravariance in universal files for more details.
+4