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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Shweta LodhaRank #31 · 39.8K reputationPosted Oct 29, 2014, 11:29 PM EDT
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
VulpesRank #55 · 29.2K reputationPosted Oct 30, 2014, 3:58 AM EDT
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.
VulpesRank #55 · 29.2K reputationPosted Oct 30, 2014, 7:11 AM EDT
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 Pariot148 reputationPosted Oct 30, 2014, 6:52 AM EDT