Conditional Operator Example

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Tue, 23 Mar 2010 08:49:19 GMT Indexed on 2010/03/23 16:03 UTC
Read the original article Hit count: 581

Filed under:

If you haven’t taken the time to learn conditional operators, then now is the time. I’ve added a quick and dirty example for those on the forums.

 

Code Snippet
  1. using System;
  2. using System.Net.Mail;
  3. using System.Net;
  4. using System.Globalization;
  5. using System.Windows.Forms;
  6.  
  7. class Demo
  8. {
  9.     //Please use conditional statements in your code. See example below.
  10.  
  11.     public static void Main()
  12.     {
  13.         int dollars = 10;
  14.  
  15.         //Bad Coder Bad !!! Don't do this
  16.         if (dollars == 1)
  17.         {
  18.             Console.WriteLine("Please deposit {0} dollar.", dollars);
  19.         }
  20.         else
  21.         {
  22.             Console.WriteLine("Please deposit {0} dollars.", dollars);
  23.         }
  24.  
  25.  
  26.         //Good Coder Good !!! Do this
  27.         Console.WriteLine("Please deposit {0} dollar{1}.", dollars, dollars == 1 ? ' ' : 's');
  28.         //                                                          expression   ? true : false
  29.  
  30.         Console.ReadLine();
  31.     
  32.     }
  33. }

© Geeks with Blogs or respective owner