Branching and Looping in C#, Part 1 - No Implicit Conversion
(Page 2 of 6 )
C# eliminates a common source of programming errors that existed in the world of C and C++, which is the implicit conversion of numeric values to Boolean values (0 to false and all the other numeric values to true). In C#, the if statement's expression must evaluate to a Boolean value, so the next block of code will not compile in C# but it will compile in C++:
int x = 10;
if(x)
{
Console.WriteLine(x);
}
In C# you will get a compile time error that states "Can't implicitly convert type 'int' to 'bool'". You need to write this block as follows:
int x = 10;
if(x > 5)
{
Console.WriteLine(x);
}
This will compile in C# because now it's a Boolean expression. Let's look at an example. The following example takes an input number from the user, tests to see if it's an even or odd number (using the module operator), and prints a line in each case.
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
Console.WriteLine("Please type a number");
int x = Convert.ToInt32(Console.ReadLine());
if(x % 2 == 0)
{
Console.WriteLine("this is an EVEN number");
}
else
{
Console.WriteLine("this is an ODD number");
}
Console.ReadLine();
}
}
}
Next: Nesting >>
More C# Articles
More By Michael Youssef