0

I'm not sure if this is better suited to programmers on SE.

I'm learning about inheritance, specifically how to use overrides - I can see I can either use override to extend the functionality or new to create new functionality.

EG

    public override int Calls(int i)
    {
        //Do some things
        return base.Calls(i);
    }

The above does the logic, and then calls the base class.

If I do new

    public new int Calls(int i)

Then I can implement my own logic, as if the base class never existed (as it's never called).

The thing which confuses me is I can simply remove the base class call from my override method and I think I get the same results as new. Meaning

public override int Calls(int i)
{
    //Do some things
    // return base.Calls(i); COMMENTED OUT, no base class call
}

The above code snippet surely is the same as public new int Calls(int i)

My question is, am i right - is this ultimately 2 ways of doing the same thing so it becomes better in terms of clarity for the developer (by using override or new) or are there any other differences between the 2 (any gotcha's).

Dave
  • 8,163
  • 11
  • 67
  • 103

1 Answers1

1

There is a massive difference between new and overrides.

In case of overrides this overwritten method is called no matter if you hold a base-class object or an object of the derived type.

with new however, the method of the derived class is called only if you hold an object of the derived class. "new" is something you should be extremely careful with, and I'm just not using it.

Martin Moser
  • 6,219
  • 1
  • 27
  • 41
  • There is no reason not to use `new`. If your child class happened to have the same method name as its parent (and they're not related), you're actually encouraged by the compiler to add the `new` keyword so the fact that they're unrelated will be explicit. I'd say you better try avoiding name collisions, not avoiding `new`. – haim770 Feb 16 '15 at 09:21