How to prevent derived class from overriding a method

Charles Sugden
Charles Sugden used Ask the Experts™
on
Good day!

I am still somewhat green to some OOP concepts so bear with my request:
I would like to create a base class that has a private method(audit) that is called from a deallocation method which I do not want to be derived/overridden. I have included the code and would like some advice on how to do this.
test.txt
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
If you don't mark it virtual, then it cannot be overridden.

Author

Commented:
When I attempt to override it (for a check) I get the message
Warning      1      'Equipment.Adder.deAllocate()' hides inherited member 'Equipment.Harness.deAllocate()'. Use the new keyword if hiding was intended.
Kyle AbrahamsSenior .Net Developer

Commented:
Make the Equipment.deAllocate virtual.

virtual bool deAllocate();

FYI . . . there's also the sealed keyword to make sure something doesn't get inheritted.
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
When I attempt to override it (for a check)...
Can you show how you did that?

Author

Commented:
käµfm³d,

I  got the error as follows:

Namespace TEDAEquipment
{
     public class Adder : PTD
     {
        public bool deAllocate()
        {
            return false;
        }
    }
}
Top Expert 2015

Commented:
Hi

http://rbwhitaker.wikidot.com/c-sharp-abstract-classes

virtual will give the derived classes the power to provide its own implementation with the word override . This is also the proof that polymorphism happens. So don't mark the method virtual so that it won't be overridden.

e.g  the word abstract ensures that you cannot create a new Player class like
        Player player = new Player();. but you can use it as
       Player player = new HumanPlayer();
________________________________________________________________look for virtual
abstract class Player
{
    public virtual MoveDirection MakeMove();
}
__________________________________________________________________look for override
namespace Inheritance
{
    class HumanPlayer : Player
    {
        public HumanPlayer()
        {
        }
 
        public override MoveDirection MakeMove()
        {
           
        }
    }
}

________________If you still want to access the base method look for base.
 MoveDirection moveDirection = base.MakeMove();
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
OK, that is what I arrived at as well. Technically speaking, what you've done isn't overriding. It's referred to as "method hiding," and as the warning you've received mentions you'd typically include the new modifier to indicate your intention to other developers.

Namespace TEDAEquipment
{
     public class Adder : PTD
     {
        public new bool deAllocate()
        {
            return false;
        }
    }
}

Open in new window


AFAIK, there is nothing that you can do to prevent this. There is a technical difference between this and overriding a method, and I'll try to think of a simple way to explain it...

Author

Commented:
So that means that the run-time can SEE the method but it cannot be overridden. Correct?
Most Valuable Expert 2015
Distinguished Expert 2018

Commented:
> When I attempt to override it (for a check) I get the message ... use the new keyword ...

But why would you proceed? If you don't want to override, then respect the warning and don't continue.

/gustav
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015

Commented:
So that means that the run-time can SEE the method but it cannot be overridden. Correct?
Yes.

It would be a rare case for you to want to use the new modifier. Even though it appears that you are inheriting the method when you use it, in reality you are not. So this breaks inheritance. It could also cause issues if you were coding against the abstraction (i.e. the base class). Take for example:

using System;

namespace ConsoleApplication68
{
    class Program
    {
        static void Main(string[] args)
        {
            Test.Harness instance1 = new Test.Harness();
            Test.Harness instance2 = new Test.Adder();

            instance1.deAllocate();
            instance2.deAllocate();

            Console.ReadKey();
        }
    }

    namespace Test
    {
        public class Adder : Harness
        {
            public new bool deAllocate()
            {
                Console.WriteLine("In Adder.deAllocate");
                return true;
            }
        }

        public class Harness : Equipment
        {
            private int _eid;

            public int eid { get { return _eid; } set { _eid = 1; } }

            public virtual int Allocate()
            {
                return 1;
            }

            public virtual bool deAllocate()
            {
                Console.WriteLine("In Harness.deAllocate");

                // Update database
                Audit();
                return true;
            }

            private void Audit()
            {
                // Update database
            }
        }

        interface Equipment
        {
            int eid { get; set; }

            int Allocate();
            bool deAllocate();

        }
    }
}

Open in new window


You might expect that you would see the message "In Adder.deAllocate" because I have a deAllocate method defined. However, because I used the new modifier, the runtime does not use the implementation that is on Adder. I have hidden it. The base class cannot "see" the implementation of deAllocate that is defined on Adder because it is not considered to be an override of the base class' method.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial