Click here to Skip to main content
Rate this: bad
good
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 at 3-Jul-13 4:26am
   
Thanks for your time dude :)
Johnny J. at 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 at 3-Jul-13 4:25am
   
Thanks my friend :)
ArunRajendra at 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 at 3-Jul-13 4:26am
   
Thanks dude :)
CPallini at 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
0 OriginalGriff 290
1 Jochen Arndt 165
2 DamithSL 125
3 PIEBALDconsult 110
4 Garth J Lancaster 90
0 OriginalGriff 5,790
1 DamithSL 4,601
2 Maciej Los 4,012
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,195


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 3 Jul 2013
Copyright © CodeProject, 1999-2014
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