Click here to Skip to main content
12,077,574 members (47,666 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# .NET Visual-Studio
Hi friends,

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

Instead of

 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.... Frown | :( :-/ :'(
Please Helppp.... !!!!
Posted 2-Jul-13 23:07pm
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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]
  Permalink  
v4
Comments
Yesudasan Moses 3-Jul-13 4:26am
   
Thanks for your time dude :)
Johnny J. 3-Jul-13 4:30am
   
NP ;-)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Yes both are perferctly fine. But considering the coding standards 1st option is more readable.
  Permalink  
Comments
Yesudasan Moses 3-Jul-13 4:25am
   
Thanks my friend :)
ArunRajendra 3-Jul-13 4:56am
   
Welcome :)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

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. Smile | :)
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160212.1 | Last Updated 3 Jul 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100