Only base method of generic called

I have the following "models":

My base class:

public abstract class Search : Model
{
    //Properties ...

    public void ShallowCopy(Search reference)
    {
        base.ShallowCopy(reference);

        //Do stuff
    }
}

My inheriting class:

public class Vehicle : Search
{
    //Properties

    public void ShallowCopy(Vehicle reference)
    {
        base.ShallowCopy(reference);

        //Do stuff
    }
}

My base "viewModel" is generic:

public abstract class MasterDataWithoutAddressViewModel<TPrimaryModel> : MasterDataViewModel<TPrimaryModel> 
    where TPrimaryModel : Search, new()
{
    public void JustAMethod() 
    {
        //do stuff

        foreach (TPrimaryModel primaryModel in primaryModels)
        {
            TPrimaryModel primaryModelCopy = new TPrimaryModel();
            primaryModelCopy.ShallowCopy(primaryModel);
            //Do more stuff
        }
    }
}

My inheriting "viewModel":

public class VehicleViewModel : MasterDataWithoutAddressViewModel<Vehicle>
{
    //...
}

With primaryModelCopy.ShallowCopy(primaryModel); I expected the ShallowCopy of Vehicle to be called. However just the method of the base class Search is called. Debugger shows that primaryModel and primaryModelCopy are both from the correct type (Vehicle).

This is the complete inheritance hierarchy of my "models": Inheritance tree

Jon Skeet
people
quotationmark

Overload resolution is performed at compile-time, and in JustAMethod it's performed once, not once per type-argument. So primaryModelCopy.ShallowCopy is resolved to the Search.ShallowCopy method.

There are two options here:

  • You could use normal polymorphism, making Search.ShallowCopy virtual, and overriding it in Vehicle.ShallowCopy (which would need to cast the parameter back to Vehicle in the method)
  • You could use dynamic typing in JustAMethod to perform overload resolution at execution-time instead. (This doesn't feel like a good idea to me, but it's an option.)

people

See more on this question at Stackoverflow