2

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); } } 
3
  • 7
    Why not null be the default? And replace it with _bar if null was passed. Commented Dec 9, 2021 at 18:26
  • 2
    If you want the non-constant value of _bar to be used as default I'd use null as formal default: void PrintBar(string value = null) and in the method's body replace null by _bar. Commented Dec 9, 2021 at 18:33
  • I question the sense in a method called "PrintBar" that might possibly not print _bar. Instead of overloading, give them different names entirely. I recognize that this might be a trivial example, but the same line of reasoning should be used to inform your design decisions in real-world scenarios, as well. Commented Dec 9, 2021 at 18:45

1 Answer 1

5

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.