Unassigned Local Variable Error

  • Thread starter Thread starter John Smith
  • Start date Start date
J

John Smith

In the following (pseudo)code, why is it that C# returns an
"unassigned local variable" error for nVar? It seems I have to
declare the variable outside foo() for the error to dissapear.

void foo()
{
int nVar = 0;

SqlDataReader rdr = objCmd.ExecuteReader();

while (rdr.Read())
{
nVar = rdr[0];
}

int nVar2 = nVar;
}

Thank you.
 
Hi John,
If you remove everything in the function body except for the line
int nVar = 0
then the compiler throws unassigned local variable warning. This is because
the compiler treats the this line as declaration and not initialization.
There might be some other error occuring in the line
nVar = rdr[0]
where unboxing is required from object to int
best,
Subin Kushle
GAPS
 
In the following (pseudo)code, why is it that C# returns an
"unassigned local variable" error for nVar?

I might be missing something since you said this is pseudo-code, but I was
able to compile it just fine (with a few obvious changes to make it
non-pseudo-code).
 
John Smith said:
In the following (pseudo)code, why is it that C# returns an
"unassigned local variable" error for nVar? It seems I have to
declare the variable outside foo() for the error to dissapear.

void foo()
{
int nVar = 0;

SqlDataReader rdr = objCmd.ExecuteReader();

while (rdr.Read())
{
nVar = rdr[0];
}

int nVar2 = nVar;
}

As it is, that's fine. If you change the first line of the body to:

int nVar;

then you would get a problem, because there's no guarantee that it
would be assigned before nVar2 tries to use it (rdr.Read() could return
false immediately).
 
Back
Top