Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Why can partial methods use ref, but not out?

Pretty straight forward. MSDN states that you can use ref, but not out for partial methods. I'm just curious as to the why? It was my understanding that when code is compiled, the partials are merged, so what is up with the restriction? Is there more to partial than just making code files cleaner and organized (i.e. eyecandy)?

Reference: MSDN Article - "Partial methods can have ref but not out parameters."

like image 344
myermian Avatar asked Aug 10 '10 20:08

myermian


1 Answers

You got to consider what happens if the partial method isn't implemented.

What happens then is that all calls to the method is just stripped out as though they never happened.

So for a method using out, it would look like this:

stream s;
GetStream(out s);
s.Write(...);

and be compiled as though it said this:

stream s;
s.Write(...);

This code is not allowed because s has not been initialized. The guarantee that the variable would be initialized by the time you try to call the Write method on it was tied up with the call to GetStream.

It is the same with methods returning data. Since the entire method call is just not compiled if you haven't implemented the partial method, you need to consider what you can and cannot do and still leave the code that calls it valid. In terms of out and return values, it has the potential of leaving the calling code invalid or incomplete, so it is not allowed.

As for ref, that is valid since the initialization has been taken care of by the calling code:

stream s = null;
GetStream(ref s); // may be stripped out
if (s != null)
    s.Write(...);
like image 60
Lasse V. Karlsen Avatar answered Sep 28 '22 07:09

Lasse V. Karlsen