Jan Tacci
Jan Tacci

Reputation: 3211

Switch statement: Not all code paths return a value

I have an enum defined as follows:

public enum CrystalTypeEnum { Red, White, Blue, Green };

and I have a static function that returns the string representation of a given enum value:

public static string toString(CrystalTypeEnum type)
{
    switch (type)
    {
        case CrystalTypeEnum.Red:
            return "Red";
        case CrystalTypeEnum.White:
            return "White";
        case CrystalTypeEnum.Blue:
            return "Blue";
        case CrystalTypeEnum.Green:
            return "Green";
    }
}

When I compile my code I get the following error:

CrystalType.toString(CrystalType.CrystalTypeEnum): not all code paths return a value

Why am I getting this error when clearly my switch statement covers all four cases (Red, White, Blue, Green).

Upvotes: 0

Views: 5503

Answers (5)

Oleg  Ignatov
Oleg Ignatov

Reputation: 865

Do not forget to use this section in switch\case construction:

switch (type) 
{
    default:
        throw new ArgumentException("Incorrect CrystalTypeEnum");
} 

Upvotes: 3

NS.X.
NS.X.

Reputation: 2142

Why am I getting this error when clearly my switch statement covers all four cases (Red, White, Blue, Green).

Because there are five cases in total not four. You can cast an integer that is not one of these defined enum values to CrystalTypeEnum type and it is still valid.

CrystalType.toString((CrystalTypeEnum)(42));

So in a switch statement default is always required?

No, you can place the return statement after the whole switch clause or anything as long as "all code paths return a value".

Upvotes: 2

AYK
AYK

Reputation: 3322

I know that the answer posted by astander, may be what you are looking for, but there is an elegnt way to do this, which wont require any switch statements.

You can use Enum.GetName method to get the string representation of an enum value. Please read here

Upvotes: 1

Peter Ritchie
Peter Ritchie

Reputation: 35870

If there is no default: control is transferred to outside of the switch statement (for values not handled by a case). This means if you don't have a default: then you need a return statement after the switch that returns a value of the type defined by the return type of the method.

Upvotes: 7

Adriaan Stander
Adriaan Stander

Reputation: 166406

You need to specify a default section.

switch (type) 
{ 
    case CrystalTypeEnum.Red: 
        return "Red"; 
    case CrystalTypeEnum.White: 
        return "White"; 
    case CrystalTypeEnum.Blue: 
        return "Blue"; 
    case CrystalTypeEnum.Green: 
        return "Green"; 
    default:
        //return what you need here
} 

Upvotes: 6

Related Questions