Home About Eric Topics SourceGear

2007-10-05 14:21:58

Shouldn't this be a compiler error?

In C#, the following method will not compile:

public bool IsOrange1()
{
}

The compiler gripes and says:

'IsOrange1()': not all code paths return a value

Which makes perfect sense.  The computer arrives at the end of this method, realizes that it is required to return a value, but does not know what value to return.  We don't want the computer to just make something up, so we have the compiler detect this case and fuss about it.

However, the following method DOES compile without errors:

public bool IsOrange2()
{
    while (true)
    {
    }
}

Which seems wrong.

I'm not saying this version deserves the same error as the previous one.  It is clear that IsOrange2 has no code paths that return while failing to define the return value.  Of course, this is because IsOrange2 has no code paths that return!

I am also not saying the compiler should error on any method that never returns.  There are reasonable uses for that sort of thing:

public void SimpleWebServer()
{
    while (true)
    {
        ListenForOneRequestAndRespondToIt();
    }
}

I am also not saying the compiler should error on any method that does nothing.  If programmers want to write code that has no purpose, the compiler shouldn't care.  This code should compile:

public void DoNothing()
{
}

And so should this:

public void WorkReallyHardAndDoNothing()
{
    while (true)
    {
    }
}

My problem is that IsOrange2 claims that it returns a value but it never does.  That just seems wrong.  I guess I expected to see:

'IsOrange2()': there are no code paths that return a value

If IsOrange2 is never going to return anything, then it should be declared void, not bool.

Maybe this doesn't really deserve an error, but I think it should be at least a warning.