Tuesday, 14 December 2010

How to use Finally Block to Dispose Variables in C#

This example demonstrate that how to use finally block to dispose object at the end of code execution. For example we have open a file "write_file.txt" to  write something but this file do not exist at particular location. now it throw the exception and in finally block we dispose the file stream object.  Instead of using finally block if we use simple dispose statement in same block so in case of exception the object will not be dispose. So to follow the best practice always use finally block to dispose the objects.

How to use Finally Block to Dispose Variables in C#

Code:

using System;
using System.IO;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream FS_out = null;
            try
            {
                FS_out = File.OpenWrite("write_file.txt");              
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (FS_out != null)
                {
                    FS_out.Close();
                    Console.WriteLine("output file stream disposed.");
                }            
            }
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment