Output parameters and the out modifier
Yesterday I was working on finishing an interface assembly in C# for one of my projects. When thinking about making the interfaces define exactly what I want them to I decided to look into the parameter types, checking to make sure I understood the semantics.
What struck me as odd, is that parameters declared with the out modifier are considered initially unassigned within a function member. This means that the following code:
void SomeMethod(out string str)
{
Console.WriteLine(str);
}
has the compiler tell you: “error CS0165: Use of unassigned local variable ’str’”. The funny thing is though, that if you change the offending line to assign something to str so it compiles (out requires you to assign something to the declared parameter before returning) and put a breakpoint on it, you’ll see that the compiler does assign the parameter, it just doesn’t allow you to use it before assigning something to it yourself. And yes, this is fully compliant with the defined semantics.
What I wonder though, is why are out parameters considered initially unassigned? It’s not a strange scenario where you want to define a parameter that for instance returns the type of a conversion and may initially contain a requested type to convert to. If you don’t pass anything you get default conversion (and a specification of what was picked in the output parameter).
If you declare such a parameter without any modifier and it’s a reference type, you won’t be able to assign something new to it since that won’t be returned. Declaring it with the ref modifier forces you to always supply something in advance, which means you need to define what value denotes “no value supplied”. And finally, declaring it with the out modifier means you’ll be able to supply an input value but the callee will never be able to use it.
My conclusion: the language designers probably want to force me out of using parameters this way.