Tony D
Tony D

Reputation: 1531

Cannot Convert Derived Class to Base Class

I am working on a transportation problem and cannot leap this hurdle. I am unable to convert the derived class StopsVisited to its base class Stops. The base class Stops is a collection of Stop. The derived class StopsVisited is a collection of StopVisited.

The element StopVisited derives from Stop (definitions not shown).

I have a non-generics workaround where I simplly derive StopsVisited from Stops, but the generics afford me more felixibility. I've tried to reduce it to its simplest form.

Base

public abstract class Stops<T> where T : Stop 
{

}

Derived

public class StopsVisited : Stops<StopVisited>
{

}

The problem:

Stops<Stop> stops = new StopsVisited();

Gives me a

Error 1 Cannot implicitly convert type 'StopsHeirarchy.StopsVisited' to 'StopsHeirarchy.Stops'

Any help is appreciated.

Upvotes: 1

Views: 3948

Answers (3)

Craig Stuntz
Craig Stuntz

Reputation: 126547

StopsVisited is not a subtype of Stops<Stop>; it's a subtype of Stops<StopVisited>, which is an entirely different thing. I agree with duffymo that subtyping is the wrong approach to your problem, but the specific feature you're asking about is called "covariance" or "output-safe" in C# 4; you can read about it here.

Upvotes: 5

duffymo
duffymo

Reputation: 308753

Personally, I wouldn't use inheritance to say that a Stop has been visited. I'd have a boolean data member to say that a Stop had been visited. It seems like a binary attribute - you've either been visited or you haven't.

Inheritance ought to be about different behaviors. Unless you can say that a visited Stop somehow behaves differently, I would advise against inheritance in this design.

Upvotes: 3

Liz
Liz

Reputation: 3043

C# 4.0 solves this problem by modifying the CLR to support it.

In the meantime, have an IStops interface (non-generic) and convert to it.

Upvotes: 0

Related Questions