Problem
In C#, what’s the equivalent of Java’s final?
Asked by Nosrama
Solution #1
In Java, there are multiple uses for the final keyword. It can be used to represent both the sealed and readonly keywords in C#, depending on the context.
To avoid subclassing (inheritance from the given class), use the following code:
Java
public final class MyFinalClass {...}
C#
public sealed class MyFinalClass {...}
Prevent a virtual method from being overridden.
Java
public class MyClass
{
public final void myFinalMethod() {...}
}
C#
public class MyClass : MyBaseClass
{
public sealed override void MyFinalMethod() {...}
}
A noteworthy distinction between the two languages here, as Joachim Sauer points out, is that Java by default marks all non-static methods as virtual, whereas C# identifies them as sealed. As a result, in C#, you simply need to use the sealed keyword to prevent future overriding of a method that has been defined as virtual in the base class.
To limit the number of times a variable can be assigned:
Java
public final double pi = 3.14; // essentially a constant
C#
public readonly double pi = 3.14; // essentially a constant
As an aside, the readonly keyword varies from the const keyword in that it evaluates the readonly expression at runtime rather than build time, allowing for arbitrary expressions.
Answered by Noldorin
Solution #2
It all depends on the situation.
Answered by LukeH
Solution #3
What everyone here is missing is Java’s guarantee of definite assignment for final member variables.
Every feasible execution route through every constructor of C for a class C with a final member variable V must assign V exactly once; failing to assign V or assigning V two or more times will result in an error.
The compiler will happily leave readonly members unassigned or enable you to assign them many times within a constructor if you use the readonly keyword in C#.
Final and readonly are not the same thing (at least in terms of member variables) – final is much stricter.
Answered by Some guy
Solution #4
As mentioned, sealed is an equivalent of final for methods and classes.
The rest is a bit more complex.
To summarize, there is no direct equivalent of final in C#. While Java misses some of the pleasant features of C#, it’s interesting for me as a Java programmer to understand where C# falls short.
Answered by Vlasec
Solution #5
final final final final final final final final final final final final final final final final final final final final final final final final final final final final -> readonly for runtime constants, const for compile time constants in Java.
No equivalent for Local Variable final and method argument final
Answered by Vijayakumarpl
Post is based on https://stackoverflow.com/questions/1327544/what-is-the-equivalent-of-javas-final-in-c