Reputation: 33
I have a function that is getting called by another part of the code, with the signature:
public override bool DoSomething(Foo f, out string failed)
{
failed = "I failed";
_anotherClassMethodExpectingString.SetString(failed);
}
So my question is - If i need to send the other class method the same string that my caller is expecting back in its "out" parameter, can i just send it the same variable, without having any effect on my caller? The "out" parameter is a little confusing to me .. Should I have used something like this instead:
public override bool DoSomething(Foo f, out string failed)
{
string localStr = "I failed";
failed = localStr;
_anotherClassMethodExpectingString.SetString(localStr);
}
Upvotes: 1
Views: 84
Reputation: 3961
The out parameter is like pointer of the object in c++. So if you don't use 'out' definer ,doesn't change value of the parameter.
Upvotes: 0
Reputation: 4917
If a parameter is declared for a method without ref
or out
, the parameter can have a value associated with it. That value can be changed in the method, but the changed value will not be retained when control passes back to the calling procedure.
Given that strings are immutable in .NET, it is safe to pass failed
to any method without ref
and out
on the string parameter and be sure it won't be changed.
Upvotes: 0
Reputation: 35117
Unless the subsequent method you're calling is also using an out parameter then there's no need to define a local variable. The string will be unaffected by any regular parameter passing.
Upvotes: 2
Reputation: 126854
If you do not expect or do not desire for your method's caller to see any alteration from the third method, what you have is fine. If I am reading your question correctly, this seems to be your intent.
If you wanted your caller to reflect changes introduced by the third method, it would need to be an out
parameter there as well, or instead return the modification via a return value which you would then assign to your original out parameter prior to returning.
Upvotes: 1