Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

instantiating class

Status
Not open for further replies.

mp89

Programmer
Sep 17, 2004
35
GB
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
 
Found the solution - setting the class to null when it is declared.


Mike
 
well.. you could try to have something like
Code:
Object myObject = new Object();
switch (blabla)
{
    case 'aaa': myObject = new myClassAaa(); break;
    case 'bbb': myObject = new myClassBbb(); break;
    case 'ccc': myObject = new myClassCcc(); break;
}

then later on, either use System.Reflection namespace to call methods by using string as name, or Convert.ChangeType to change the object type to the class you need.



--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
Sounds likely that in any case where one of the switch conditions isn't met, then there would be some sort of error anyway?

In which case set the class to null in the default block of the switch statement. This should cover all possible paths of execution, and provide you with a means of testing if something has gone horribly wrong. Which it never should. of course ;-)
 
The curly-brackets introduce a new variable scoping level. So any variables you declare inside them is not visible outside the brackets.

Thus, you need to declare your variable outside the brackets, and instantiate it inside them.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top