c# 8 switch expression: No best type was found for the switch expression

You should explicitly declare a type of handler, instead of var

IHandler handler = key switch //or BaseHandler handler = key switch
{
    "myhandler1" => new MyHandler1(),
    "myhandler2" => new MyHandler2(),
    _ => throw new NotImplementedException()
};

In your sharplab sample both handlers implement IHandler interface and inherit BaseHandler class, compiler simply doesn't know which type to use, you should tell it him explicitly

interface IHandler { }
public class BaseHandler { }
public class MyHandler1 : BaseHandler, IHandler { }
public class MyHandler2 : BaseHandler, IHandler { }

The same is true for the dependency injection sample, you should explicitly declare a type (assuming that Handler1 and Handler2 implement IHandler)

return key switch
{
    Constants.Brand => sp.GetService<Handler1>(),
    Constants.Series => (IHandler) sp.GetService<Handler2>(),
    _ => throw new NotImplementedException()
};

You can do it only for one constant, compiler is smart enough to do the rest of job for you


You're dealing with a covariance issue. You've specified that the return type of the Func should be IHandler, but this type param is invariant. As such, you have to actually return IHandler, not just a class that implements it.

serviceCollection.AddTransient<Func<string, IHandler>>(sp => key =>
{
    return key switch
    {
        Constants.Brand => (IHandler)sp.GetService<Handler1>(),
        Constants.Series => (IHandler)sp.GetService<Handler2>(),
        _ => throw new NotImplementedException()
    };
}