I have just written a function and I don't understand why I'm getting the result I am:
private void ReplaceIfEmpty(string originalValue, string newValue)
{
if (string.IsNullOrWhitespace(originalValue))
{
originalValue= newValue;
}
}
When I call this function the originalValue is not updated. My understanding is that a string is a class, therefore it's a reference type, therefore the value I pass in should be updated. Can you explain why it isn't?
This has nothing to do with reference types vs value types really.
You're changing the value of a parameter:
originalValue= newValue;
For "normal" parameters which don't have the ref
or out
modifier, that change will never be visible.
See my article on parameter passing for more information, along with my article on reference types and value types to make sure you understand why sometimes it "looks" like reference types are passed by reference by default. (They're not: all arguments are passed by value by default, it's just that for reference types, the argument value is a reference, not an object, so changes made to the object are still visible from the caller.)
So you could make originalValue
a ref
parameter - but it would be better to make the method return a string
instead. I'm generally reluctant to use ref
parameters; code is usually easier to understand without them.