What is the equivalent of Java’s final in C#?
What is the equivalent of Java’s final in C#?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
finalkeyword has several usages in Java. It corresponds to both thesealedandreadonlykeywords in C#, depending on the context in which it is used.Classes
To prevent subclassing (inheritance from the defined class):
Java
C#
Methods
Prevent overriding of a
virtualmethod.Java
C#
As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as
virtual, whereas C# marks them assealed. Hence, you only need to use thesealedkeyword in C# if you want to stop further overriding of a method that has been explicitly markedvirtualin the base class.Variables
To only allow a variable to be assigned once:
Java
C#
As a side note, the effect of the
readonlykeyword differs from that of theconstkeyword in that thereadonlyexpression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.