Zhobday
Zhobday

Reputation: 31

missing return statement in factory pattern c#

I have the following code for my code but it always says the return statement is missing, even though I have put them in a switch list.

public IMap Map(string oldtheme) 
{ 
    switch (oldtheme) 
    { 
        case "archer": return new Archer(); 
        case "craftyblue": return new CraftyBlue(); 
        case "minimal": return new Minimal(); 
        case "mintalicious": return new Mintalicious(); 
        case "misfit": return new Misfit(); 
        case "peach": return new Peach(); 
        case "queen": return new Queen(); 
        case "sketch": return new Sketch(); 
        case "takeaway": return new TakeAwayLemonFresh(); 
        case "lemonfresh": return new TakeAwayLemonFresh(); 
        case "vanilla": return new Vanilla(); 
        case "velvet": return new Velvet(); 
        case "victoriana": return new Victoriana(); 
        case "writer": return new Writer();
    }
}

Upvotes: 2

Views: 181

Answers (4)

Andre Korosh Kordasti
Andre Korosh Kordasti

Reputation: 425

You have to use break after every return command and it will work fine.

Upvotes: 0

Wai Ha Lee
Wai Ha Lee

Reputation: 8805

You need to handle the case when oldtheme is none of the values you check for.

Depending on your case, I suggest throwing a ArgumentException so you know when it happens. I have added a default case to your switch statement:

public IMap Map(string oldtheme)
{
    switch ( oldtheme )
    {
        case "archer": return new Archer();
        case "craftyblue": return new CraftyBlue();
        case "minimal": return new Minimal();
        case "mintalicious": return new Mintalicious();
        case "misfit": return new Misfit();
        case "peach": return new Peach();
        case "queen": return new Queen();
        case "sketch": return new Sketch();
        case "takeaway": return new TakeAwayLemonFresh();
        case "lemonfresh": return new TakeAwayLemonFresh();
        case "vanilla": return new Vanilla();
        case "velvet": return new Velvet();
        case "victoriana": return new Victoriana();
        case "writer": return new Writer();
        default: throw new ArgumentException("unexpected value of oldtheme");
    }
}

Upvotes: 4

Dion V.
Dion V.

Reputation: 2120

You lack a default value. Just add;

default: return null;

At the bottom of your switch and you'll be fine.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77304

What do you want to return if the string is none of those you have in your switch? Your function is missing a return statement for that case.

Upvotes: 0

Related Questions