Justin
Justin

Reputation: 379

What does it take to override a function in .NET

I was asked this in an interview today and I just can't figure it out. I was asked everything from beginning to advanced questions, but this one stuck out. I was describing inheritance and polymorphism and then this question came up. I have obviously never tried to override every method in a [C# / C++] class, but I wasn't aware there was something that was required in order to override a particular method (.ToString, for example). Did I misinterpret the question or is there something required? And if so, what forces this requirement?

Upvotes: 3

Views: 235

Answers (5)

user470714
user470714

Reputation: 2888

If you understand polymorphism and inheritance, then I feel like maybe you're overthinking the question. I mean C# override is simply like this:

  public override double parentFunction() 
  {
     //child implementation
  }

... and the parent function must be delcared as virtual.

Without hearing the question verbatim, it's hard to say what the interviewer was looking for. My experience with interviewers is that they're just looking to make sure you understand the generalities, but who knows. I'd be curious to find out if you get the job : ) Good luck!

Upvotes: 0

amurra
amurra

Reputation: 15401

The method that you want to override must be marked virtual or abstract.

Upvotes: 0

Matt Davis
Matt Davis

Reputation: 46052

In C++ and C#, you have to declare the base-class function as virtual. Otherwise, a function in a derived class that has the same name and signature will hide the base class version.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564631

The method you are overriding must be declared as virtual or abstract (and be in a non-sealed type). Otherwise, your only option is to hide it.

Upvotes: 1

jeroenh
jeroenh

Reputation: 26782

  • the base class must not be sealed
  • the method in the base class must be marked as virtual or abstract

Upvotes: 9

Related Questions