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 contructor:
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: 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 CreateGelper()?
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.