C# Else Statement

Else keyword

What is there to know about the else keyword? Else, which is found in an else-if statement as well as a plain else statement, represents an alternative in the if selection statement. One interesting puzzle, pondered here, is whether to use a return statement at the end of an else block.

This C# example program uses the else keyword. Else is described in more detail.

Examples

This program introduces method A and method B. They both do the exact same thing, and have equivalent performance and intermediate representation. Method A uses a return statement at the end of an else block; method B omits the else block.

Program that shows return-after-else [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(A(5));
	Console.WriteLine(B(4));
    }

    static bool A(int y)
    {
	if (y >= 5)
	{
	    return true;
	}
	else
	{
	    return false;
	}
    }

    static bool B(int y)
    {
	if (y >= 5)
	{
	    return true;
	}
	return false;
    }
}

Output

True
False

Return-after-else

Question and answer

Perhaps one of the most important questions in programming, computer science, and the universe is whether to use a return statement in an else-block. If you omit the else, you lose symmetry but reduce the size of the source code. Probably the key deciding factor is what the most common pattern is in the code base you are working on.

Summary

The C# programming language

The else keyword in the C# language is found in many but not all programs that use if-statements. No else if, or else, is required, but 'else' is useful when alternative cases are required. In a switch statement, the default keyword can be used as a substitute for else.

Switch Statement If Statement
.NET