Re: use of unassigned local variable

From: Richard Blewett [DevelopMentor] (richardb_at_develop.com)
Date: 10/19/04


To: microsoft.public.dotnet.languages.csharp
Date: Tue, 19 Oct 2004 05:31:46 -0700

Posting the offending code would be useful, but I guess you have simething like this:

 Foo f;

 switch( i )
 {
     case 1:
         f = new Foo(42);
         break;
     case 2:
         f = new Foo("Hello");
 }

 f.DoSomething(); // this causes the error

 The issue is the compiler doesn't know whether any of the cases will have resulted in the creation of a Foo to assign to teh reference so it is uninitialized as far as the compiler is concerned.

 So change the first line to:

 Foo f = null;

 This is now initialized to a known value (null) it doesn't have to be hooked up to an instance, just set to a known value.

 Regards

 Richard Blewett - DevelopMentor
 http://staff.develop.com/richardb/weblog

   I am instantiating a class in a switch statement as there are a number
 of different overloads depending upon the data entered by the user.
 
 The problem I have is that after instantiating my class, when I try to
 call methods in the class later on in my code using the same object I
 cannot, I get the error 'use of unassigned local variable'.
 
 How do I get around this as I need some sort of switch/if statement to
 instantiate my class?
 
 
 Any assistance would be really appreciated.
 
 
 Cheers,
 
 Mike



Relevant Pages

  • Re: Which GoF Design Pattern to choose?
    ... BY instantiating the right ... Using a switch here may be unavoidable. ... your application in which you are dealing with raw data. ...
    (comp.programming)
  • Re: why is this happening ?
    ... Some consider it a wart on Tcl since you have to think long and hard to understand it's advantages. ... switch $foo { ... Because inside the switch, ...
    (comp.lang.tcl)
  • Re: "Did not find leading dereferencer" - new findings to an old puzzle
    ... You presumably don't want to rewrite your code not to use Switch; ... given ($foo) { ... But I would hardly recommend using bleadperl, or even one of the 5.9.x ... the source file is around 350 lines big. ...
    (comp.lang.perl.misc)
  • Re: [PHP] switch vs elseif
    ... tedd wrote: ... one may not notice immediately the missing break statement. ... switch($foo) ...
    (php.general)
  • Re: The Big Switch
    ... my switch example may have been a bit to simple. ... 0x01 {puts foo} ... So the switch works if you can be sure to have the string 0x01 in the ... set cmd [lindex $opcodes $index] ...
    (comp.lang.tcl)