Summary : if I create an object in the constructor initializer, how do I keep a reference to it so that I can refer to it later?
More details
I have a class ( LibBase , below) for which StreamWriter is required as its construction parameter. I do not have the source code for LibBase - it is in a third-party library.
public class LibBase { public LibBase(System.IO.StreamWriter wtr) { ... } }
I got MyClass from LibBase and in the MyClass constructor I want to pass an instance of MyWriter (a derived form of StreamWriter ) to the base class. I do it as follows.
public class MyWriter : System.IO.StreamWriter { public MyWriter(int n) { ... }
The problem is that MyWriter needs to be disposed of, so MyClass must dispose of it (and implement IDisposable for this) , but MyClass does not have a link to the created instance of MyWriter , so I cannot dispose of it . The constructor initializer syntax does not seem to allow me to save the link.
My solution is to transcode MyClass as follows:
public class MyClass : LibBase, IDisposable { public MyClass(Encoding enc) : this(new MyWriter(enc)) { } private MyClass(MyWriter wtr) : LibBase(wtr) { this.wtr = wtr; }
The private constructor stores a reference to an instance of MyWriter , so I can use it later.
My questions are :
- What am I missing here? I feel like I'm struggling with the tongue. Does C # provide a better way to do this?
- If the language does not support this directly, is there a better solution than the method of my private constructor?
- Any comments about defects in my solution?
source share