C# cannot implicitly convert type when types are the same

I have a generic class:

public abstract class ModelSet<T> : ObservableCollection<T>, IModelObject where T : ModelObject, new(){

    public static ModelSet<T> Lookup(long pObjectId){
       return (ModelObjectMap.Get(pObjectId) as ModelSet<T>);
   }
}

I have the following class instantiation of the type using a class Movement defined as:

class Movement : ModelObject.

public partial class Movements : ModelSet<Movement>

The following code won't compile due to

cannot implicitly convert type ModelSet<Movement> to Movements. An explicit conversion exists.

Movements X = Movements.Lookup(12345);

Surely, they are the same. What am I doing wrong?

Jon Skeet
people
quotationmark

Surely, they are the same.

No, they're not the same. One is Movements, and the other is ModelSet<Movement>. While every Movements instance is an instance of ModelSet<Movement>, it's entirely possible to have a ModelSet<Movement> which isn't a Movements... and your method's return type only says that it will return a ModelSet<T>.

We have no idea what ModelObjectMap.Get(pObjectId) actually does, but it could definitely return a ModelSet<Movement> instance which isn't a Movements.

We don't know what you need to do with the return value, but you could certainly write:

ModelSet<Movement> X = Movements.Lookup(12345);

... although it's worth noting that the Movements class actually isn't involved in that call at all; it would actually be compiled to:

ModelSet<Movement> X = ModelSet<Movement>.Lookup(12345);

people

See more on this question at Stackoverflow