loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 

C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

Ternary operators simplified

by naspinski 3/22/2008 1:53:00 AM

For a while there, I would see mystical things happening in some code I viewed, and I had no idea what was happening - turn out the bla?bla:bla does mean something, and it is useful and simple

These?are:called ternary operators, and they can be very useful, especially when you want to clean up your code.  A lot of people say that they are hard to read, but I think that is merely because they do not understand how simple they really are. I will show you just how simple they are; here is a statement using a ternary operator:

 

a ? b : c ;

 

And all this means in simple terms is:

 

if a is true, then b is the value of the statement, else c is the value of the statement

 

or if you prefer code:

 

if(a)
  return b;
else
  return c;

 

That really is it, it is that simple. Ternary operators can save a lot of space, and more important (to me) they can easily be used inline, cutting out chunks of code completely.  Take a look at the following for an example:

string s1 = "party";
string s2 = "crom";
string s3 = "arnold";
bool b1 = true;
bool b2 = false;
string s4, s5;

//All of this code:
if (b2)
  s4 = s1;
else
  s4 = s2;

if (b1)
  s5 = s1;
else
  s5 = s2;

//can be replaced by this
s4 = b2 ? s1 : s2;
s5 = b1 ? s1 : s2;

//plus you can easily use it inline
Response.Write("inline = " + (b2 ? s2 : s3).ToString());


You can make them much deeper and more complicated and then they may begin to get difficult to read, but for a lot of everyday tasks, ternary operators are great and space saving!

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

c# | tutorials

Related posts

Add comment

Name*
E-mail* (Gravatar)
Website
Country   Country flag

Comment* [b][/b] - [i][/i] - [u][/u]- [quote][/quote]




Live preview

11/19/2008 4:18:57 AM