Connecting Tech Pros Worldwide Forums | Help | Site Map

Use of unassigned local variable 'fout'

Newbie
 
Join Date: Jul 2009
Posts: 1
#1: Jul 1 '09
Some body please help me.
I finds this code really correct.
However I am a beginner
The following code yields

Use of unassigned local variable 'fout' error in my pgm please help

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. namespace ConsoleApplication6
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             FileStream fout;
  14.  
  15.             try
  16.             {
  17.  
  18.                 fout = new FileStream(@"C:\abc1.txt", FileMode.Open);
  19.             }
  20.             catch(Exception exc)
  21.             {
  22.                 Console.WriteLine("0.Error on access"+exc.Message);
  23.             }
  24.  
  25.             try
  26.             {
  27.                fout.WriteByte((byte)'F'); 
  28.             }
  29.  
  30.             catch(Exception exc)
  31.             {
  32.                 Console.WriteLine("1.Error on write "+ exc.Message);
  33.  
  34.             }
  35.             fout.Close();
  36.             Console.ReadLine();
  37.  
  38.         }
  39.     }
  40. }

tlhintoq's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 1,783
#2: Jul 1 '09

re: Use of unassigned local variable 'fout'


Line 13 you never assign anything to fout, so it is still null.
LIne 18 you try to assign something to it, but that has the potential to fail leaving fout at null
Line 27 then tries to use that yet-to-be-assigned fout
Expert
 
Join Date: Jan 2008
Location: York
Posts: 179
#3: Jul 2 '09

re: Use of unassigned local variable 'fout'


A better way to do it, as WriteByte is dependent on you opening the FileStream correctly.
Expand|Select|Wrap|Line Numbers
  1. try
  2.             {
  3.                 fout = new FileStream(@"C:\abc1.txt", FileMode.Open);
  4.                 fout.WriteByte((byte)'F'); 
  5.             }
  6.             catch(Exception exc)
  7.             {
  8.                 Console.WriteLine("0.Error "+exc.Message);
  9.             }
  10.             finally
  11.             {
  12.                 if(fOut != null) {fOut.Close()};
  13.             {
  14.  
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#4: Jul 2 '09

re: Use of unassigned local variable 'fout'


Right, you don't have to set up a try block for each potential failure, you can use one try with multiple catches (each for a different type of Exception) if you want.
Reply