-
May 23rd, 2010, 11:52 PM
#1
Return and IF statement error?
This code comes up with "Return retrunvalue does not exist in the current context"?
How do i fix this?
public bool enrolCheck(Paper p, Student s)
{
for (int i = 0; i < papersEnrolled.Count; i++)
{
string names = papersEnrolled[i].ToString();
if (names == p.ToString())
{
bool returnvalue;
returnvalue = true;
}
}
return returnvalue;
-
May 23rd, 2010, 11:58 PM
#2
Re: Return and IF statement error?
You need to move your definition for returnvalue. As is it goes out of scope when the code gets to the next } leaving it invalid when it gets to the line that tries to return it.
You need to move the definition outside of the for block if you want to access it once the For is complete. Here you would need to move it to the line just before you begin your for { }
Code:
public bool enrolCheck(Paper p, Student s)
{
bool returnvalue;
for (int i = 0; i < papersEnrolled.Count; i++)
{
string names = papersEnrolled[i].ToString();
if (names == p.ToString())
{
returnvalue = true;
}
}
return returnvalue;
}
Last edited by DataMiser; May 24th, 2010 at 12:03 AM.
Always use [code][/code] tags when posting code.
-
May 24th, 2010, 01:26 AM
#3
Re: Return and IF statement error?
Tried that and it gives me an "unassigned local variable" on the return returnvalue;
public bool enrolCheck(Paper p, Student s)
{
bool returnvalue;
for (int i = 0; i < papersEnrolled.Count; i++)
{
string names = papersEnrolled[i].ToString();
if (names == p.ToString())
{
returnvalue = true;
}
}
return returnvalue;
-
May 24th, 2010, 02:06 AM
#4
Re: Return and IF statement error?
Whatever DataMiser saying correct. Variables will loose its scope once coming out of the {}. But do remember that any local variable in .Net should have assigned values to use that variables. We cannot use an unassigned variable. That means, if you are declaring an integer it should be assigned with some values before leaving the scope.
Code:
public bool enrolCheck(Paper p, Student s)
{
bool returnvalue = false;
for (int i = 0; i < papersEnrolled.Count; i++)
{
string names = papersEnrolled[i].ToString();
if (names == p.ToString())
{
returnvalue = true;
}
}
return returnvalue;
}
There are changes that, the for loop may end up with 0 iterations or the if may fail to get a match. In that case retrurnValue will not be having values assigned to it to be returned. So while declaring the variable we will have to assign the default value to it.
Regards,
Jayashree K R
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|