C Sharp

How C# Enforces if Rules

One aspect of the if statement that catches new C# programmers off guard is the fact that the expression evaluated must result in a Boolean value. This is in contrast to languages such as C++ where you're allowed to use the if statement to test for any variable having a value other than 0. The following example illustrates several common errors that C++ developers make when attempting to use the if statement in C# for the first time: -

using System;
interface ITest
{
}
class TestClass : ITest
{
}
class InvalidIfApp
{
    protected static TestClass GetTestClass()
    {
        return new TestClass();
    }
    public static void Main()
    {
        int foo = 1;
        if (foo) // ERROR: attempting to convert int to bool.
        {
        }
        TestClass t = GetTestClass();
        if (t) // ERROR: attempting to convert TestClass to bool.
        {
            Console.WriteLine("{0}", t);
            ITest i = t as ITest;
            if (i) // ERROR: attempting to convert ITest to bool.
            {
                // ITest methods
            }
        }
    }
}

If you attempt to compile this code, you'll receive the following errors from the C# compiler: -

invalidIf.cs(22,7): error CS0029: Cannot implicitly convert type 'int' to 'bool'
invalidIf.cs(27,7): error CS0029: Cannot implicitly convert type 'TestClass' to 'bool'
invalidIf.cs(31,14): warning CS0183:
The given expression is always of the provided ('ITest') type
invalidIf.cs(32,8): error CS0029: Cannot implicitly convert type 'ITest' to 'bool'

As you can see, the compiler barks three times in response to three attempts to use the if statement with an operation that doesn't yield a Boolean value. The reason for this is that the C# designers want to help you avoid ambiguous code and believe that the compiler should enforce the original purpose of the if statement-that is, to control the flow of execution based on the result of a Boolean test. The example above is rewritten below to compile without error. Each line that caused the compiler error in the previous program has been modified to contain an expression that returns a Boolean result, thereby appeasing the compiler.

using System;
interface ITest
{
}
class TestClass : ITest
{
}
class ValidIfApp
{
    protected static TestClass GetTestClass()
    {
        return new TestClass();
    }
    public static void Main()
    {
        int foo = 1;
        if (foo > 0)
        {
        }
        TestClass t = GetTestClass();
        if (t != null) 
        {
            Console.WriteLine("{0}", t);
            ITest i = t as ITest;
            if (i != null)
            {
                // ITest methods.
            }
        }
    }
}