Would anybody please tell me as the reason the following use of sealed
does not compile? Whereas, if I replace sealed
with final
and compile it as Java, it works.
private sealed int compInt = 100;
public bool check(int someInt)
{
if (someInt > compInt)
{
return true;
}
return false;
}
That's because
final
in Java means plenty of different things depending on where you use it whereassealed
in C# applies only to classes and potentially virtual members (methods, properties, events).In Java
final
can be applied to:sealed
.virtual
and in a derived class this can be prevented for further derived classes withsealed
again.readonly
.Sealed
inC#
can be applied only to a reference types, and has impact on inheritance tree.In practise the type marked as
sealed
guranteed to be the last "leaf" in the inheritance tree, or in short, you can not derive from the type declared like asealed
.It can not be applied to a members.
Tigran's answer is not wrong while Joey's is a little incorrect.
Firstly you can look into this page: What is the equivalent of Java's final in C#?.
the
sealed
key word can apply toclass
,instance method
andproperty
but not variables, or interface's methods. Classes withsealed
cannot be inherited. Whensealed
put on method, it must be byoverride
in company. Everystruct
issealed
, sostruct
cannot be inherited. Check this image: