I’ve run into an easily solved but a design problem I’ve not encountered in my young life yet.
I have a class that needs to go through a few setup procedures before anything else happens.
However, during the construction of this class, I have in the constructor’s parameters a delegate that can be passed so that the user can add their own information to the class.
When this is called however the scope that is creating the class still doesn’t have a valid instance and therefore a null exception error occurs.
How do I design around this? Should I pass an instance of “this” to that delegate?
What is a good decision to make here? I have a “StartServices()” method where I could easily put the call to the delegate but I feel design wise it should be in the constructor.
Thanks for the advice!
It sounds like you want to pass an
Action<T>(or similar), so that at whichever point the class wants the delegate, it can calltheDelegate(this); for example:Then
objwill be the instance when it is created, and it has the advantage that the compiler-generated method doesn’t require any state / capture (unless you need that yourself).However! I would cautious of calling a delegate inside a constructor, for the same reason that
virtualshould be treated with caution – in a deep object model the entire class may not be fully created at the point your mid-level constructor (that invokes the delegate or overridden method) fires, providing dodgy access to an object in an incomplete state.