1

I have created interface:

 public interface ILocationDetector
    {
        bool IsChanged { get; }

        void Detect(IEnumerable<LocationDto> locations);
    }

and the abstract class which implements the inteface

 public abstract class LocationDetector : ILocationDetector
    {
        public bool IsChanged { get; }
        //some other props..

        protected LocationDetector(MonitoredLocation monitoredLocation)
        {

        }

        public abstract void Detect(IEnumerable<LocationDto> locations);

        //some more methods...
}

I have created two class which dervied from above. I would like to create one of the instance which match my conditions. What I do is:

> ILocationDetector detector = _locationOrigin == LocationOrigin.Native
>                     ? new ADetector(monitored)
>                     : new BDetector(monitored);

This gives me an error:

Type of conditional expression cannot be determined because there is no implicit conversion between first and second

However above code works:

ILocationDetector a = new ADetector(monitored);
ILocationDetector b = new BDetector(monitored);

Can someone explain me that ?

miechooy
  • 3,178
  • 12
  • 34
  • 59

1 Answers1

2

Your ternary operator says: if condition is met then create ADectector else create BDetector without saying what base type/interface you want to use. There is no implicit conversion between these two types.

Compiler canno determine what is the correct type of expression, so you have to tell it what are the correct types by casing it.

ILocationDetector detector = _locationOrigin == LocationOrigin.Native
    ? (ILocationDetector)new ADetector(monitored)
    : (ILocationDetector)new BDetector(monitored);

Also, there is no need to case both parts(second is inferred), so this will do:

ILocationDetector detector = _locationOrigin == LocationOrigin.Native
    ? (ILocationDetector)new ADetector(monitored)
    : new BDetector(monitored);
Zbigniew
  • 27,184
  • 6
  • 59
  • 66