Search code examples
c#genericstypescovariancecovariant-return-types

c# object interface return type covariance


C# compiler:

error CS0738: Field<T>' does not implement interface memberField.Value.get' and the best implementing candidate Field<T>.Value.get' return typeT' does not match interface member return type `object'

public interface Field
{
   object Value {get;}
}

public class MyField<T> : Field
{
   T _value;
   public T Value
   {
      get
      {
         return _value;
      }
   }
}

Why ? List < T > extends List in microsoft classes, but i as a user (copying same design pattern) am not allowed to do that? why?

Trying where T: object also gives a compiler error...

How do i fix this?

the other 1.000.000 threads on the same subject, Say :
blablabla, 'return type covariance', blablabla, 'you cant'.

They do not propose a solution or a workaround on how to compile this beast. Requirements:
1) Field is an interface that cannot take generics. Evil framework called "unity" forbids generics.
2) Field < T > which "implements Field" has generic T.


Solution

  • You can implement interface explicitly. https://msdn.microsoft.com/en-us/library/ms173157.aspx

    The same pattern is used on non generic version of IEnumerable and generic IEnumerable<T>

    You can do the same and have generic interface too.

    public interface Field
    {
        object Value { get; }
    }
    
    public interface Field<T> : Field
    {
        new T Value { get; }
    }
    
    public class MyField<T> : Field<T>
    {
        public T Value { get; } // generic
    
        object Field.Value => Value; // non generic
    }
    

    Now if you have Field<T> on your hand you can use T happily. if you have Field you get object form of value T