Share via


using 'final' modifier in C#

Question

Saturday, August 3, 2013 11:32 AM

public class A
{
 private void show()
 {
  final String s="checking";
 }
}

Will someone throw some light on the use of ‘final’ modifier in the above piece of code?

Found this while navigating through a Q/A blog, where it said that we can declare a local variable

inside a method of a class to be final. The user did not explain much about its use though.

Any help will be much appreciated! Thanks in advance.

All replies (4)

Saturday, August 3, 2013 12:29 PM ✅Answered

Hi,

final is a keyword in Java, it does not exists in C#.

For the local variables C# supports only const.
A more common usage is a instance or static field with a readonly modifier.

For some equivalent usages in C# see:
http://stackoverflow.com/questions/1327544/what-is-the-equivalent-of-javas-final-in-c

Regards, Elmar


Saturday, August 3, 2013 1:37 PM ✅Answered

There is also the Finalize Method, wich is closely related to the Dipose-pattern and dealing with unmanaged Rescources:

http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

In addition to const, you can also use readonly. The difference is that readonly can (and must) be assigned once, in the Constructor or during declaration. It is also not required to a static value:

http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

Constructor Chaining is advised when using readonly.

Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.


Saturday, August 3, 2013 1:41 PM ✅Answered

Other equivalents:

Sealed takes over Final's duties for Inheritance/Polymorphy.

I think readonly is a better match for Java Final then Const.

Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.


Saturday, August 3, 2013 1:25 PM

Finally can only be used in an exception handler

        static void Main(string[] args)        {            try            {            }            catch            {            }            finally            {            } 

jdweng