I am having a little bit of an issue with some Razor C# code syntax.
I have a form which has it’s action as “website.cshtml”. website.cshtml should take all of the data passed in, and print it out in
tags.
Here is what I have :
@{
string names = Request.Form["name"];
string [] arrOfnames; // string array to hold names
if (names != null) { // if the name isn't null, split into the array
arrOfNames = names.Split(',');
}
foreach(string name in names)
{
<p>name</p>
}
}
This results in the error
Use of unassigned local variable ‘arrOfNames’.
What have I done incorrectly here and how can I fix it?
That C# compiler error results when there is a chance that a local variable is read from before it has been assigned to. (I am assuming the code is really
for (var name in arrOfNames)– hint! – orarrOfNamesis accessed later.)It (
arrOfNames) must be assigned on all possible code paths (as determined by compiler).What if
names == null? What wouldarrOfNamesbe then? C# ensures that you are explicit about this.One method is to ensure a value is assigned in the “alternate path”:
but
or
or
would also work.
I would recommend having an “empty collection” vs.
null, as empty enumerable object can still be iterated over, as happens in the next few lines. On the other hand, perhaps it should die a ugly horrid death…Also, consider using the interface
IEnumerable<string>as it is often more accommodating to code changes. (Especially when used as part of a method signature.)Happy coding.