How to pass a private variable as the default optional parameter in C#

Viewed 97

In the provided example, the function declaration PrintBar is throwing an error because _bar is not a compile time constant. What is the best practice to avoid this issue?

using System;

class Foo
{
    private readonly string _bar;
    public Foo(string initBar)
    {
        _bar = initBar;
    }

    public void PrintBar(string value = _bar)
    {
        Console.WriteLine(value);
    }
}
1 Answers

I suggest overloading esp. in case Dmitry's solution (using null as default and then assign _bar if null passed) is not a way out (when null can well be passed as a valid input):

public void PrintBar(string value)
{
    Console.WriteLine(value);
}

public void PrintBar() => PrintBar(_bar);
Related