3

I have some code like this:

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Save([Bind(Prefix="")]Person person) { String s = person.property; /* ... */ } 

But it throws the error: "Cannot use local variable 'person' before it is declared".

What simple thing am I missing?

3 Answers 3

17

It is most likely that you are receiving this error because the same variable is being declared later in the same code block.

According to compiler rules, a variable reference will refer to default by a matching declaration withing the same block EVEN IF THE SAME DECLARATION EXISTS OUTSIDE OF THE BLOCK IN IN LOGICAL SCOPE FLOW.

So in short, check to see if the variable isnt being declared later on(a couple of lines down) in the same application block.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I get that, but this was on the first line - the only declaration was a string on said line and the parameter. Still just a rare bug probably related to some weird compilation thing.
Thank you. It's in moments like this that one feels dumb. Should have checked my code!
4

Okay, this is just some really bizarre error - if the variable is named a particular name it does not work, for any other name it does work...

2 Comments

By closing the question, you (and anyone else that comes after) now have no chance of understanding the "really bizarre error", which undoubtedly has a rational explanation. By closing the question you weaken Stackoverflow! Cheers, Rob
Fair enough, I assumed it was something I was doing specifically wrong and non-applicable to others.
2

I had the same problem with a declared variable named endingYear.

Declared here:

 public ChartData(MetricInfo metricInfo, MetricItem[] metricItems) : this() { int endingYear = 0; 

Further along in the method this was not a problem:

 endingYear = endingDate.Year; 

But when I referenced the very same varable in a Case statement I got the "Cannot use local variable before it is declared" error even thou the variable was in intelesense:

 case "QRTR_LAST_FULL_QRTR": if (metricInfo.CalendarType == "CALENDAR") { switch (endingDate.Month) { case 1: case 2: case 3: loopControl = 4; endingYear = endingDate.Year - 1; 

Based on Matt's result I tried changing the variable name to endYear and the problem went away. Very strange and a waste of a half hour or so. If it was not for this thread of posts it probably would have been a bigger time loss.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.