What is the correct way to initiate a class in a class? should I put StreamWriter in a method? or this is fine?
class Class1
{
public static string config = "file.config";
StreamWriter writer = new StreamWriter(config);
public void print (string log)
{
writer.WriteLine(log);
}
public void log_close()
{
writer.Close();
}
}
Your closing logic is not thread-safe and does not follow recommendations.
You should use the Disposable pattern because FileStream implements IDisposable.
And now your Class1 instances can be use with the
usingstatement:No need to call Dispose() or close().