I have 3 lines that go
int selectedOrgId;
foreach (Organization o in PD.orgs)
if (o.orgname == selectedOrgName)
selectedOrgId = o.orgid;
PD.cats.InsertOnSubmit(new Category {
orgid = selectedOrgId,
catname = newCatName
});
The middle line, the loop, is guaranteed, in the context of my program, to set a value for selectedOrgId
. However, Visual Studio is flagging the last line because
Use of unassigned local variable 'selectedOrgId'
What is a way to solve this other than
int selectedOrgId = 69;
foreach (Organization o in PD.orgs)
if (o.orgname == selectedOrgName)
selectedOrgId = o.orgid;
PD.cats.InsertOnSubmit(new Category {
orgid = selectedOrgId,
catname = newCatName
});
????
Although it works, it seems like an inelegant solution, since it involves a magic number. I want to know the proper C# style of solving this.
EDIT:
Looking at some of the discussion here, I should've specified that there is only such orgid
in the database. My foreach
statement should've been written like
foreach (Organization o in PD.orgs)
{
if (o.orgname == selectedOrgName)
{
selectedOrgId = o.orgid;
break;
}
}
Thanks for showing me some ways to better do this whole thing!