19

I've used the @Override in java and has come in quite handy. Is there anything similar in c#?

Community
  • 1
  • 1
xecaps12
  • 5,316
  • 3
  • 27
  • 42
  • 5
    I dunno, the `override` keyword? – BoltClock May 17 '11 at 03:01
  • 2
    Ok, sorry, that was a really stupid question. I was looking for an annotation but couldn't find one. Forgot it was part of the method signature. Still a bit new to c#. – xecaps12 May 17 '11 at 03:06
  • 1
    C# actually had the `override` keyword first. It proved useful enough that they added the feature as an annotation to Java. – Gabe May 17 '11 at 03:11

4 Answers4

14

The C# compiler provides compile-time checking for method overrides, including checking if the method is actually overriding as you intended. You can indicate that a method should be overridden using the .NET override keyword.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
4

In C#, you must use the override keyword to override functions.

If you use override without a matching virtual or abstract base function, you'll get a compiler error.

If you don't use override, and there is a matching base function, you'll get a compiler warning (unless you add new).

Quanta
  • 465
  • 5
  • 14
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

In CSharp, override keyword meaning is totally different from the Java world. The equivalent in Csharp World is explicit implementation but it has a drawback.

interface IShape
{
     void Display();
}

class Square : IShape
{
     void IShape.Display()
     {

     }
}
Mohan Kumar
  • 621
  • 1
  • 8
  • 25
-3

No, yes. It makesn o sesne to have an anotation because in C# there is an override kkeyword in the langauge and the compiler warnds if you "hide" a method. So, either you say "new" or "override" directly as part of the method.

Java basically uses the annotation to hide a mistake in the langauge specifications.

Please read the language specificastions for C#. Completely.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • 1
    Why is it a mistake? There is really nothing about overriding that any modern compiler can't work out on its own. I find it mostly useful from a self-documenting perspective, and having to explicitly declare my intent makes me keep track of things. But is it necessary for compilation? Not really. – drharris May 17 '11 at 03:13
  • 1
    C# also does not have it for "the compiler" but to be explicit. Overriding without warning is a possible error condition. Java made the mistake to make everything virtual by default and auto override, and it introduces a ton of possible errors. – TomTom May 17 '11 at 07:45
  • 1
    So what? ;) Only sheep have no opinion, and they get slaughered. I personally think if you want a weak typed langauge, go and get one. Otherwise... it is a weak point. – TomTom May 17 '11 at 19:45