I have the following: a base class SystemBody (which has 3 readonly fields that must be set in the contructor, and never get changed in the object's lifetime), arbitrary derived classes from SystemBody, and the following generic method:
public T AddBody<T>(SystemBody parentBody) where T : SystemBody, new()
{
T rtn = new T(this, ++currentID, parentBody != null ? parentBody.id : -1);
Which results in:
error CS0417: 'T': cannot provide arguments when creating an instance of a variable type
I am struggling to understand what I'm intended to do in this situation.
SystemBody has a constructor with the signature required, but I have no way to enforce that a constructor with that signature exists in T. (C# seems to be noticeably lacking a generic type constraint for having a constructor with any arguments)
I can't use an initializer (which does work as expected if the properties are public) because they're readonly. (An initializer would be my preferred choice)
Using public int id {get; private set;}
has identical results to public readonly int id;
The only solution I can think of is to add an Initialize
method to the base class which takes the parameters I need to set - this feels like a gross hack that doesn't feel like it conforms to the way C# code should be written.
What am I missing? Do I just have to write Initialize?