To my surprise, this one compiles and runs:
class Program
{
static void Main()
{
DoSomething();
}
private const int DefaultValue = 2; // <-- Here, private.
public static void DoSomething(int value = DefaultValue)
{
Console.WriteLine(value);
}
}
The method is public whereas the default value "redirects" to a constant private variable.
My question:
What is/was the idea behind this "concept"?
My understanding (until today) was, that something public can only be used if all other "referenced" elements are also public.
Update:
I just ILSpy-decompiled my class to find:
static class Program
{
private static void Main()
{
Program.DoSomething(2);
}
private const int DefaultValue = 2;
public static void DoSomething(int value = 2)
{
Console.WriteLine(value);
}
}
So if the private constant as a default parameter is being done in e.g. a library, the user of the library still sees the default parameter.
The name DefaultValue
is private, but the number 2
is still the number 2
.
Because DefaultValue
is private, we cannot access Program.DefaultValue
from outside of Program
. Presumably we wouldn't particularly want to.
And because we've bothered to define DefaultValue
at all, it's presumably something that we do care about when we are working on how Program
works.
So when we come to define a default value for DoSomething
there's presumably some logical reason why the value we want there happens to be the same as the value DefaultValue
.
And as such, it's presumably beneficial to be able to use that constant there, for much the same reasons as we would find constants beneficial anywhere.
And since DefaultValue
is just a Program
-specific way of saying 2
, there's no real reason why we can't.
Of course, the metadata would reflect this as 2
rather than the (meaningless to the outside) DefaultValue
, but then that would hold if the const
was public
anyway (the metadata about default values gives only the value, not whether or not it related to any defined constants).
So there's no downside.
So considering that:
2
.Why not?