15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

38 ❘ ChaPTer 2 cOre c#<br />

If more than one statement is to be executed as part of either condition, these statements need to be joined<br />

together into a block using curly braces ({.}). (This also applies to other <strong>C#</strong> constructs where statements<br />

can be joined into a block, such as the for <strong>and</strong> while loops):<br />

bool isZero;<br />

if (i == 0)<br />

{<br />

isZero = true;<br />

Console.WriteLine("i is Zero");<br />

}<br />

else<br />

{<br />

isZero = false;<br />

Console.WriteLine("i is Non-zero");<br />

}<br />

If you want to, you can use an if statement without a final else statement. You can also combine else if<br />

clauses to test for multiple conditions:<br />

using System;<br />

namespace Wrox<br />

{<br />

class MainEntryPoint<br />

{<br />

static void Main(string[] args)<br />

{<br />

Console.WriteLine("Type in a string");<br />

string input;<br />

input = Console.ReadLine();<br />

if (input == "")<br />

{<br />

Console.WriteLine("You typed in an empty string.");<br />

}<br />

else if (input.Length < 5)<br />

{<br />

Console.WriteLine("The string had less than 5 characters.");<br />

}<br />

else if (input.Length < 10)<br />

{<br />

Console.WriteLine("The string had at least 5 but less than 10<br />

Characters.");<br />

}<br />

Console.WriteLine("The string was " + input);<br />

}<br />

}<br />

There is no limit to how many else ifs you can add to an if clause.<br />

code snippet ElseIf.cs<br />

You’ll notice that the previous example declares a string variable called input, gets the user to enter text at<br />

the comm<strong>and</strong> line, feeds this into input, <strong>and</strong> then tests the length of this string variable. The code also shows<br />

how easy string manipulation can be in <strong>C#</strong>. To find the length of input, for example, use input.Length.<br />

One point to note about if is that you don’t need to use the braces if there’s only one statement in the<br />

conditional branch:<br />

if (i == 0) Let's add some brackets here.<br />

Console.WriteLine("i is Zero"); // This will only execute if i == 0<br />

Console.WriteLine("i can be anything"); // Will execute whatever the<br />

// value of i<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!