Hi,
I did many times but not able to declare variable in side my IF-ELSE. Please tell me where I am making a mistake.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Shweta LodhaPosted Oct 30, 2014, 3:29 AM
As per .Net, you can not declare variable inside IF condition. That's the reason you are facing an error. To get rid of this error, please declare your variable outside IF and then use that inside IF condition. That will work.
Bit more info: Reason behind this is that IF expects an expression, not a statement. If you wanna know more, check this link:
http://msdn.microsoft.com/en-us/library/aa664742(v=vs.71).aspx
VulpesPosted Oct 30, 2014, 11:11 AM
As a correct answer had already been posted, I only posted myself to add something which I thought might be of interest to you or other members reading the thread.
Graeme PariotPosted Oct 30, 2014, 10:52 AM
VulpesPosted Oct 30, 2014, 7:58 AM
If you're talking about the condition, then you simply can't do it as Shweta said.
However, you CAN declare variables in the body of an 'if' statement. The only restriction is that they must not have the same name as local variables declared in an 'outer' scope because there would be no way to access the latter if this were allowed.
So, this program compiles and works fine:
However, if you uncomment the second 'if' statement, then it won't compile because the 'j' which is local to the 'if' statement would conflict with the 'j' which is local to the method as a whole.