final keyword example in c sharp
The finally Block
A finally block always executes—whether or not an exception is thrown and whether or not the try block runs to completion. finally blocks are typically used for cleanup code.
A finally block executes either:
• After a catch block finishes
• After control leaves the try block because of a jump statement (e.g., return or
• After the try block ends
A finally block helps add determinism to a program. In the following example, the file that we open always gets closed, regardless of whether:
• The try block finishes normally.
• Execution returns early because the file is empty (EndOfStream).
• An IOException is thrown while reading the file.
example of final given below:
static void ReadFile()
StreamReader reader = null; // In System.IO namespace
reader = File.OpenText (“file.txt”);
if (reader.EndOfStream) return;
if (reader != null) reader.Dispose();
In this example, we closed the file by calling Dispose on the StreamReader. Calling Dispose on an object, within a finally block, is a standard convention throughout the .NET Framework and is supported explicitly in C# through the using statement.
The using statement Many classes encapsulate unmanaged resources, such as file handles, graphics handles, or database connections. These classes implement System.IDisposable, which defines a single parameterless method named Dispose to clean up these resources. The using statement provides an elegant syntax for calling Dispose on an IDisposa
ble object within a finally block.
using (StreamReader reader = File.OpenText (“file.txt”))
is precisely equivalent to:
StreamReader reader = File.OpenText (“file.txt”);
if (reader != null)