I have a function that uses out parameters to return multiple values to the caller. I would like to initialize them i开发者_运维百科n the function, but I wasn't sure if that's a bad idea since you don't know when you call the function that it's going to change the values right away. The caller might assume that after the function returns, if whatever it was doing didn't work, the values would be whatever they were initialized to in the caller.
Is it ok / good for me to initialize in the function?
Example:
public static void SomeFunction(int ixID, out string sSomething)
{
sSomething = "";
sSomething = something(ixID);
if (sSomething = "")
{
somethingelse();
sSomething = "bar"
}
}
Yes - with an out parameter you must assign it before returning.
Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.
You don't need to initialize them to empty values at the very top of your function though. You can assign the values when you know them. In your example the first line is not needed as you assign to the out parameter in the second line.
I'm pretty sure the answer is yes, you should initialize them in the function because as I was doodling up the example in my Q, Visual Studio complained that I must assign sSomething
before returning.
精彩评论