John Ryann
John Ryann

Reputation: 2393

c# constructor and streamwriter

I would like to create a generic logger class. This complains "value cannot be null.Parameter name:path". After I initialize the object I get the logname value but not log. where did I do wrong?

class Logger
{

    public static string log;


    public Logger(string logname)
    {
        log = logname;

    }
    StreamWriter writer = new StreamWriter(log);
}

Upvotes: 0

Views: 313

Answers (1)

kmatyaszek
kmatyaszek

Reputation: 19296

Try this:

...
    public Logger(string logname)
    {
         log = logname;
         writer = new StreamWriter(log);
    }
    StreamWriter writer = null;
...

You have this error because first is executed following line:

StreamWriter writer = new StreamWriter(log);

And in that moment field log is null because constructor is executed after fields initialization.

Upvotes: 10

Related Questions