Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override an generic method?(C#)

I'm creating a class named TetraQueue that inherits System.Collections.Generic.Queue class overriding the Dequeue method, here is the code:

public class TetraQueue : Queue<Tetrablock>
{
   public override Tetrablock Dequeue()
   {
       return base.Dequeue();
   }
 }

But when I try to compile this I get:

Error TetraQueue.Dequeue()': no suitable method found to override TetraQueue.cs

Thanks in advance.

How do I know if a method is virtual(to avoid this kind of situation)?

like image 315
Diones Avatar asked Dec 06 '25 02:12

Diones


1 Answers

Two ways to know whether or not a method is virtual:

  • Type in "override" in Visual Studio - it will offer you all the methods you're allowed to override.
  • View the documentation - Dequeue doesn't say it's virtual, so you can't override it.

EDIT: Others have suggested hiding the method. I strongly recommend that you don't do that unless you really, really have to. It's a recipe for difficult debugging sessions and frustration when inheritance appears to sometimes work and sometimes not, depending on the compile-time type of the reference. Blurgh. If you're not going to specialize the behaviour, use composition instead of inheritance.

like image 179
Jon Skeet Avatar answered Dec 07 '25 18:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!