- Home /
How to cast without using a helper function
Please help me understand why one option below will work but the other will not.
public T GetService<T>() {
try {
MonoBehaviour mono = serviceReferences[typeof(T)];
//return (T) mono; // Does not work
return Cast<T>(mono); // Does work
}
catch(KeyNotFoundException) {
throw new ApplicationException("The requested service is not registered");
}
}
public T Cast<T>(object input) {
return (T)input;
}
Answer by mxoconnell · May 12, 2019 at 03:46 AM
Here's an option...
public T GetService<T>() where T : MonoBehaviour, new() {
if(!serviceReferences.ContainsKey(typeof(T))) {
Debug.LogError("Could not find service: " + typeof(T) + ". Crash imminent!");
return new T();
}
return (T)serviceReferences[typeof(T)];
}
There~s no point in requesting a constructor or to create an instance with new since we deal with $$anonymous$$onoBehaviours. Just applying the constraint to $$anonymous$$onoBehaviour is enough. Though it depends on what type the serviceReferences dictionary contains.
Generics work quite different from C## Templates even the syntax look different. Generics need to be compilable with any type. The actual type binding happens at runtime. That's why in most cases constraints on the type parameter are necessary. Otherwise one could pass "int" as type which the compiler knows is impossible. In some cases you would even need a double cast(first to object, then to T). This is essentially what that helper function did. Since the parameter was of type object any inco$$anonymous$$g type is implicitly upcasted to object.
Your answer
![](https://koobas.hobune.stream/wayback/20220612201219im_/https://answers.unity.com/themes/thub/images/avi.jpg)