1

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#?

Andrey Tsarev
  • 769
  • 1
  • 8
  • 25
  • 1
    Read this question about the [New vs Override](https://stackoverflow.com/questions/1399127/difference-between-new-and-override) keywords. You can't override base methods unless they are declared as `abstract` (on an abstract class) or `virtual`. – ProgrammingLlama Dec 04 '18 at 01:19
  • Also, I recommend explaining what "it doesn't work" actually means in your scenario. – ProgrammingLlama Dec 04 '18 at 01:20
  • @John Thanks that answers my question. I will edit it so other people can see it and try to clarify. – Andrey Tsarev Dec 04 '18 at 01:25

1 Answers1

1

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)

Andrey Tsarev
  • 769
  • 1
  • 8
  • 25