Single Line If Statement in C#

One of the very first aspects a programmer learns is how to write an if statement. By this, we know a basic if statement (code snippet below) and the string result will be assigned Welcome.

string fname = "Victor";
string result = "";
if(fname == "Victor")
{
  result = "Welcome";
}
else
{
  result = "Access Denied";
}

As a first step, since the if and else both only have one line of text each, we know that the code above can be shortened and still have the same result.

string fname = "Victor";
string result = "";
if(fname == "Victor")
  result = "Welcome";
else
  result = "Access Denied";

or even

string fname = "Victor";
string result = "";
if(fname == "Victor") result = "Welcome";
else result = "Access Denied";

Now, there is an even shorter way to express the previously shown code:

string fname = "Victor";
string result = (fname == "Victor") ? "Welcome" : "Access Denied";
Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

2 Responses to “Single Line If Statement in C#”

  1. very easy way,,,,

    thanks

  2. Yunus says:

    Thanks for this post.
    if you had showed only the last way, it wouldnt be very affective for new programmers.
    Thanks again.

Leave a Reply