Click here to Skip to main content
11,637,002 members (73,261 online)
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 22: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 stibee 313
1 jyo.net 295
2 OriginalGriff 263
3 Sergey Alexandrovich Kryukov 240
4 Suvendu Shekhar Giri 225
0 OriginalGriff 8,941
1 Sergey Alexandrovich Kryukov 8,493
2 Mika Wendelius 6,909
3 F-ES Sitecore 2,388
4 Suvendu Shekhar Giri 2,320


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