- Home /
Question by
cliftint · Jun 04, 2013 at 12:45 PM ·
c#genericsconstraints
Are generic constraints supported?
I have a small dependency injection utility which works fine in Visual Studio but fails to build in Unity. It has a function looking like this:
public void RegisterSingleton<T1, T2>() where T2 : T1
{
T2 singleton = Get<T2>();
RegisterSingleton<T1>(singleton);
}
Which fails on the second line with:
Assets/Util/DependencyInjector.cs(80,13): error CS1503:
'`Argument `#1' cannot convert `T2' expression to type `T1'.
This indicates it isn't usually knowledge of the constraint to permit the conversion of T2 to T1. My only work-around so far is to just force the cast:
public void RegisterSingleton<T1, T2>() where T2 : T1
{
object singleton = Get<T2>();
RegisterSingleton<T1>((T1) singleton);
}
I see other Unity examples of generic constraints so is there any reason for this to not work?
Comment