I have a function that uses out parameters to return multiple values to the caller. I would like to initialize them in 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.
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.