I'm creating a TryGetComponent(Type type, out Component component) method, and then adding a TryGetComponent<T>(out T component) overload for convenience:
public bool TryGetComponent(Type type, out Component component)
{
component = null;
if (type.IsAssignableFrom(typeof(Component)))
{
throw new ArgumentException($"Must get component using a type that is assignable to {nameof(Component)}: Parameter type was '{type}'", nameof(type));
}
return Components.TryGetValue(type, out component);
}
public bool TryGetComponent<T>(out T component) where T : Component
{
return TryGetComponent(typeof(T), out component);
}
But I get the following compile error regarding ```out component`` in the second function.
Cannot convert from out T to out component
Adding an explicit cast to T gives the following error
The out parameter must be assigned before control leaves the current method.
I'm almost certain I've done this exact pattern before. No idea why it's not compiling.
As John Wu said in his comment, every
Tis aComponent, but not everyComponentis aT.It looks like you're trying to achieve the following:
T, and either return false or throw if that component is not aT.(whether you want to return false or throw is not clear because the implementation is not complete. You can modify my code to do whichever you prefer)
In your second method, you're trying to simply call the first method, but you need extra logic to check if that component is a
Tand than handle that.Update: @Charlieface pointed out that the inner call specifies
typeof(T)anyway, so we can assume the component is aT. But this can't be known at compile time, so we still need logic to cast it:Old example:
So, something like: