In C#, if you have multiple constructors, you can do something like this:
public MyClass(Guid inputId, string inputName){ // do something } public MyClass(Guid inputId): this(inputId, 'foo') {}
The idea is of course code reuse. However, what is the best approach when there is a bit of complex logic needed? Say I want this constructor:
public MyClass(MyOtherClass inputObject) { Guid inputId = inputObject.ID; MyThirdClass mc = inputObject.CreateHelper(); string inputText = mc.Text; mc.Dispose(); // Need to call the main Constructor now with inputId and inputText }
The caveat here is that I need to create an object that has to be disposed after use. (Clarification: Not immediately, but I have to call Dispose() rather than waiting for Garbage Collection)
However, I did not see a way to just call the base constructor again if I add some code inside my overloaded constructor. Is there a way to call the base constructor from within an overloaded one?
Or is it possible to use
public MyClass(MyOtherClass inputObject): this(inputObject.ID, inputObject.CreateHelper().Text) {}
Would this automatically Dispose the generated Object from CreateHelper()?
Edit: Thanks so far. Two problems: I do not control MyOtherClass and I do not have Extension Methods (only .NET 3.0…). I do control my own class though, and since I’ve just started writing it, I have no problem refactoring the constructors if there is a good approach.
The most common pattern used to solve this problem is to have an Initialize() method that your constructors call, but in the example you just gave, adding a static method that you called like the code below, would do the trick.