Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi friends,

I want to know if I can use "if statement" like this
C#
 if ( listView1.SelectedItems.Count >0 && MessageBox.Show("Remove this Contact?", Application.ProductName, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
//Some Code here...
}


Instead of

C#
 if ( listView1.SelectedItems.Count >0)
      if(MessageBox.Show("Remove this Contact?", Application.ProductName, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
//Some Code here...
}

I want it to get the Message Box confirmation only if the selected items count is greater than 0....
Both working fine now..... But I am afraid if any problems will occur in future.... :( :-/ :'(
Please Helppp.... !!!!
Posted

As far as I know, the fist one is completely valid as well. It will check the first statement and only check the next statement if the first one is true...

[EDIT] I found the proof on MSDN[^] [/EDIT]
 
Share this answer
 
v4
Comments
Yesudasan Moses 3-Jul-13 4:26am    
Thanks for your time dude :)
Johnny J. 3-Jul-13 4:30am    
NP ;-)
Yes both are perferctly fine. But considering the coding standards 1st option is more readable.
 
Share this answer
 
Comments
Yesudasan Moses 3-Jul-13 4:25am    
Thanks my friend :)
ArunRajendra 3-Jul-13 4:56am    
Welcome :)
if conditional expression is evaluated (and short-circuited, see "&& Operator (C# Reference)"[^] ) left to right. So first and second forms are equivalent and you don't have to worry about future. :-)
 
Share this answer
 
v2
Comments
Yesudasan Moses 3-Jul-13 4:26am    
Thanks dude :)
CPallini 3-Jul-13 4:33am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900