- Home /
This question was
closed Feb 08, 2015 at 11:40 PM by
meat5000 for the following reason:
The question is answered, right answer was accepted
Question by
Yarbrough8 · Feb 08, 2015 at 11:22 PM ·
c#constructor
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();
Comment
Best Answer
Answer by Alanisaac · Feb 08, 2015 at 11:26 PM
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 break
s;
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();
}
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer
C# Constructor in MonoBehaviour 1 Answer