Link to home
Start Free TrialLog in
Avatar of deniX23
deniX23

asked on

try {} assignment

Hi,
How come when i do an assignment inside a try{} block and afterwards try to use the assigned variable it tells me I am using it without assigning?
Take this for example:
----------------------------
int a;
try{a=some_function();}
catch(Exception e)
{<some code>}
MessageBox.Show(a.ToString ());
-----------------------------------
I get the error message when compiling: Use of unassigned local variable 'a' (in the MessageBox line)

If i were to insert the line 'a=5' before the 'try' it would compile and work fine.
Am i missing something here?
ASKER CERTIFIED SOLUTION
Avatar of razo
razo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of noulouk
noulouk

Hi denix23,

With int, you have to assigned a value when you declare the variable:
int a=0;
particulary if you use try {}.

Another way possible:
try{
int a;
a=some_function();
MessageBox.Show(a.ToString ());              ----Or myfunction() to do what I want.
}
catch(Exception e)
{<some code>}

Hope this will help you.