In this example assume we have a class:
public class Test
{
int a;
int b;
int c;
public Test(int a = 1, int b = 2, int c = 3)
{
this.a = a;
this.b = b;
this.c = c;
}
}
All parameters are optional so that the user can instantiate the class using either
Test test = new Test(a:a, c:c);
Or whatever the user chooses without having to pass all or even any parameters.
Now say we want to add another optional parameter StreamWriter sw = new StreamWriter(File.Create(@"app.log"));
(I assume this is correct syntax for instantiating the StreamWriter class).
Obviously as a required arguement I can add it to the constructor like so:
public Test(StreamWriter sw, int a = 1, int b = 2, int c = 3)
But what should I do if I want it to be an optional parameter? The following:
public Test(int a = 1, int b = 2, int c = 3, StreamWriter sw = new StreamWriter(File.Create(@"app.log")))
Isn't an option as you receive the following error:
"Default parameter value for 'sw' must be a compile-time constant"
Is there another way I can make sw
an optional parameter without receiving this error?