Andrey Tsarev
Andrey Tsarev

Reputation: 779

Overriding method in Class Extending Collection with Generic C#

I am doing some courseworks and I can't figure how to override a method after extending from a class. I am trying to override it by using the new keyword, but base method is still invoked.

public class TrainList : ObservableCollection<Train>
{
    ...

    public new void Add(Train train)
    {
        Console.WriteLine("Contains ID: " + ContainsId(train.Id).ToString());
        if (!ContainsId(train.Id)) base.Add(train);
    }

    ...
}

ViewModel:

public class AddTrain
{
    // Possible values for selectable items
    public ObservableCollection<Station> Stations => Facades.StationList.Instance;
    public ObservableCollection<Train> Trains => Facades.TrainList.Instance;
    public void InsertTrain()
    {
        ....
        Train newTrain = trainBuilder.build();
        Console.WriteLine("Created an object");
        Trains.Add(newTrain);
    }
}

How can one override a method from extended class when there are generics in c#?

Upvotes: 1

Views: 60

Answers (1)

Andrey Tsarev
Andrey Tsarev

Reputation: 779

Changing

public ObservableCollection<Train> Trains => Facades.TrainList.Instance;

to

public Facades.TrainList Trains => Facades.TrainList.Instance;

solves the problem.


The problem here is that the ViewModel is casting the object to ObservableCollection. Therefore, the new method is not invoked.

Reference: New vs override keywords (Thanks to @John)

Upvotes: 1

Related Questions