Changing parameter values is considered an anti-pattern, but I find it useful sometimes with optional parameters in C#:
public void Foo(int p1, MyClass fooObj = null)
{
if (fooObj == null)
{
fooObj = LoadFooObj(....
}
. . .
}
Is something here potentially harmful I may be missing?
Thanks.
That's absolutely fine. In fact, it's a good way of making a parameter optional without having to bake in the value as a constant.
You can use the null-coalescing operator to make it slightly more readable though:
fooObj = fooObj ?? LoadFooObj();
You could even consider using the same approach for value types:
public void Log(string message, DateTime? timestamp = null)
{
DateTime actualTimestamp = timestamp ?? DateTime.UtcNow;
...
}
One downside of this is that it prevents null
from being used as a "normal" meaningful value though - consider whether or not you will ever need that in a particular context.
See more on this question at Stackoverflow