0

I wondered if you can write final (Java) functions/methods in C#. Can I see some examples of C# final functions/methods?

There is the opposite question here.

Community
  • 1
  • 1
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200

1 Answers1

5

As opposed to Java, all methods in C# are final by default. If you want to make a method overridable, you need to mark it as "virtual".

If a method is marked as virtual in a base class, and further down the hierarchy you want to mark it as "final", you should use the sealed keyword.

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • So this is the complete opposite concept than in Java where everything is virtual/overridable by default and you must specify final classes. In C# everything is final by default and you must specify when you want something virtual/overridable. Fun... – Bastien Vandamme Jul 15 '14 at 10:25
  • 2
    @B413 Correct. IMO, marking all methods as *final* by default was a good design decision. Why create a vtable for all types, when only a handful of them need one? – dcastro Jul 15 '14 at 10:27
  • 1
    _all methods in C# are final by default_. Umm... This is not completely true because C# can hide the base class methods with `new`. Whereas Java's `final` is truly final. – sampathsris Jul 15 '14 at 10:37
  • 1
    @Krumia Interesting difference. You can't prevent method hiding in c# (however since the perpetrator has to write `new` explicitly and sicne hiding is less powerful than ovveriding I personally see no problem with this). – Nathan Cooper Jul 15 '14 at 10:50
  • 1
    @NathanCooper: I don't see a problem either. In my opinion C#'s design is elegant and flexible. – sampathsris Jul 15 '14 at 10:54
  • 1
    @Krumia Hiding a method does not remove the method, and it does also not change the way the original method works. However, it makes it harder for people (in some cases) to call it. It also makes things pretty confusing. It is not recommendable to hide a method. Instead, choose an unused name for the new method. – Jeppe Stig Nielsen Jul 15 '14 at 11:25