1

I have a C# viewmodel to which I'm passing a generic type in the constructor:

public ViewModelTestPage(IIncrementalLoadingHelper<MessageDTO> incrementalLoadingHelper)
    {
        IncrementalLoadingHelper = incrementalLoadingHelper;
    }

In my ViewModel base class I have the following property:

public IIncrementalLoadingHelper<BaseDTO> IncrementalLoadingHelper {get; set;}

MessageDTO inherits from BaseDTO.

On the line which sets IncrementalLoadingHelper = incrementalLoadingHelper, I'm getting an error:

Cannot implicitly convert type IIncrementalLoadingHelper<MessageDTO> to IIncrementalLoadingHelper<BaseDTO>. An explicit conversion exists (are you missing a cast?)

I probably am missing a cast, but I have no idea how to do this. Could someone point me in the right direction, please?

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Russty
  • 283
  • 1
  • 3
  • 6
  • The formatting messed up the real error:- Cannot implicitly convert type 'IIncrementalLoadingHelper' to 'IIncrementalLoadingHelper'. An explicit conversion exists (are you missing a cast?) – Russty Nov 20 '16 at 01:43
  • 1
    Possible duplicate of [Covariance and contravariance real world example](http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example) – romain-aga Nov 20 '16 at 01:45
  • Does MessageDTO descend from BaseDTO? What does the definition of IncrementalLoadingHelper look like? – Robb Vandaveer Nov 20 '16 at 01:55

1 Answers1

0

All you actually need is a generic out modifier on the generic type:

    class BaseDTO { }
    class MessageDTO : BaseDTO { }
    interface IIncrementalLoadingHelper<out T> { }

    class ViewModelTestPage
    {
        IIncrementalLoadingHelper<BaseDTO> IncrementalLoadingHelper { get; }

        public ViewModelTestPage(IIncrementalLoadingHelper<MessageDTO> incrementalLoadingHelper)
        {
            IncrementalLoadingHelper = incrementalLoadingHelper;
        }
    }

That said, it doesn't make much sense to me that the property is of the base type, but the constructor takes the derived type. Why not just use the derived type as the property type then?

Asik
  • 21,506
  • 6
  • 72
  • 131