Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overridden base method conditionally in C#

Tags:

c#

inheritance

I've never really been poised with this question: But would it be a terrible crime to call base.SomeMethod() conditionally in an overridden method?

Example as in:

protected override void SomeMethod()
{ 
     if( condition > 0 ) 
        base.SuperMethod(); 
}

I'm aware that this may be considered bad practice but I've actually never read such a claim so far.

like image 501
Ralph Caraveo Avatar asked Oct 27 '09 18:10

Ralph Caraveo


4 Answers

I can't think of a reason why this would be bad off the top of my head.

It'd be a lot worse to override the base method and copy the base method's functionality to conditionally call instead of just calling the base method.

like image 124
kemiller2002 Avatar answered Sep 23 '22 15:09

kemiller2002


class HardHearingPerson : Person
{
  override void Listen() 
  { 
    if (volume.Acceptable()) 
      base.Listen(); 
  }
}

Guess it depends on the context, but I am sure it could have justified usage.

like image 27
leppie Avatar answered Sep 24 '22 15:09

leppie


I do this quite often. Every time I need to "do something more" in a method I override it do my stuff and invoke the base method (or vice versa)

like image 28
Sergio Avatar answered Sep 21 '22 15:09

Sergio


I think it is totally acceptable. You might want to override the behaviour of a base class method only under certain circumstances, or extend the behaviour by calling the base method then doing your own thing.

like image 36
Philip Wallace Avatar answered Sep 23 '22 15:09

Philip Wallace