Search code examples
c#collectionsnullablenon-nullable

Is it somehow possible to create a collection of Foo<T> objects where T is restricted to a non-nullable type?


Inside of a class I have the following struct

private struct StateGroup<TState> where TState : struct, IAgentState
{
    // ...
    // ComponentDataArray requires TState to be a struct as well!
    public ComponentDataArray<TState> AgentStates;
    // ...
}

and multiple objects of that type

[Inject] private StateGroup<Foo> _fooGroup;
[Inject] private StateGroup<Bar> _barGroup;
[Inject] private StateGroup<Baz> _bazGroup;
// ...

with the Inject attribute just marking target for automated dependency injection.

Inside the class I need to call the very same chunk of code for each StateGroup object and I want to add all of into a collection and iterate over it. However I cannot define any collection of type StateGroup<IAgentState>[] since it requires a non-nullable type parameter and I must not remove the struct from the where clause since the ComponentDataArray of StateGroup requires a struct as well!

Besides writing a method I manually call a dozen times for each StateGroup object, is there any reasonable way to add those to a collection and call that particular method for each element?


Solution

  • You can create another interface for StateGroup<TState> without the struct constraint:

    private interface IStateGroup<TState> where TState : IAgentState { }
    

    Then we make StateGroup to implement the new interface:

    private struct StateGroup<TState>: IStateGroup<IAgentState> where TState: struct, IAgentState { }
    

    And testing:

    var states = new List<IStateGroup<IAgentState>>();
    var fooGroup = new StateGroup<Foo>();
    var booGroup = new StateGroup<Boo>();
    var mooGroup = new StateGroup<Moo>();
    states.Add(fooGroup);
    states.Add(booGroup);
    states.Add(mooGroup);