variable scope inside a method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I'm having trouble with variable scope inside procedures.
this is pseudocode

LDAP NewUser;

if (something = true)
{
NewUser = LDAP.FindUser(use emailaddress)
this.textbox1 = NewUser.name
}
else
{
NewUser = LDAP.FindUser(use employeeID)
this.textbox1 = NewUser.name
}

I'd rather have this:

if (something = true)
{
NewUser = LDAP.FindUser(use emailaddress)
}
else
{
NewUser = LDAP.FindUser(use employeeID)
}

this.textbox1 = NewUser.name

however: i get the error unassigned use of NewUser. How do I declare NewUser
so that I can have access to its members outside of the if..else statement?

my real code has dozens of textboxes to fill and I don't want to duplicate
the same
statments twice.

thanks

chris
 
Chris,

You would do this:

LDAP NewUser = null;

And then the rest of your code.

Hope this helps.
 
Hi,

There is no need to set the variable to null , as it';s assigned in both
branches of the IF statement the compiler will not complain about it.

So the "use of unassigned variable" is not for that reason.

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation



Nicholas Paldino said:
Chris,

You would do this:

LDAP NewUser = null;

And then the rest of your code.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Chris said:
Hi,

I'm having trouble with variable scope inside procedures.
this is pseudocode

LDAP NewUser;

if (something = true)
{
NewUser = LDAP.FindUser(use emailaddress)
this.textbox1 = NewUser.name
}
else
{
NewUser = LDAP.FindUser(use employeeID)
this.textbox1 = NewUser.name
}

I'd rather have this:

if (something = true)
{
NewUser = LDAP.FindUser(use emailaddress)
}
else
{
NewUser = LDAP.FindUser(use employeeID)
}

this.textbox1 = NewUser.name

however: i get the error unassigned use of NewUser. How do I declare
NewUser
so that I can have access to its members outside of the if..else
statement?

my real code has dozens of textboxes to fill and I don't want to
duplicate
the same
statments twice.

thanks

chris
 
Back
Top