Can I store a reference to a constructor in C#?

switch(inputType)
{
case InputType.Pointer: return new PointerInput(); break;
case InputType.Keyboard : return new KeyboardInput(); break;
case InputType.Gamepad: return new GamepadInput(); break;
default: Debug.LogWarning(“No input type set. Using defaults.”); return new PointerInput();
}

This switch case gives me a warning “unreachable code detected”, which makes perfect sense to me. So is there a way that I could store my constructors (new PointerInput() etc.) like a variable und write a better switch statement like so:

SomeType constructor;

switch(inputType)
{
	case InputType.Pointer: constructor = new PointerInput(); break;
	case InputType.Keyboard : constructor = new KeyboardInput(); break;
	case InputType.Gamepad: constructor = new GamepadInput(); break;
	default: Debug.LogWarning("No input type set. Using defaults."); constructor = new PointerInput();
}

return new constructor();

I think you’re misinterpreting the error.

Each of your return ...; statements is followed by a break; statement in the switch/case. Since a return statement will already exit the switch/case, you don’t need any of those breaks;

 switch(inputType)
{
case InputType.Pointer: return new PointerInput();
case InputType.Keyboard : return new KeyboardInput();
case InputType.Gamepad: return new GamepadInput();
default: Debug.LogWarning("No input type set. Using defaults."); return new PointerInput();
}