views:

180

answers:

3

Something like:

  • if the value of the variable after the method call has to be returned :
  • if can be instantiated before the method call use ref
  • if does not need to be instantiated before the call use out

  • if the value of the variable is used for returning , deciding or calculating other values from the method call do not use ref neither out

Did I get it correctly ? What is your short guideline ?

A: 

Not sure if this is really answering your question but one good usage of passing a value by ref (using the out keyword) I have found is...

int i = 0;

if (int.TryParse("StringRepresentation", out i)
{
    // do something with i which has taken the value of a the previous successful TryParse
}
Nick Allen - Tungle139
+2  A: 

For value types :

  • If you just want to use the value contained AND NOT alter it in the original place use the default passing method (by value)
  • If you need to alter it in the original store, use ref. Example :

    int a = -3;

    protected void EnsurePositiveValues(ref int value) { if (value < 0) value = 0; }

For reference types :

  • If you need to just use the instance or alter it use the default passing method (by reference ; should be called "by reference copy")
  • If you need to (re)assign in the original reference then use ref. Example :

    User u = MembershipAPI.GetUser(312354);

    protected void EnsureUser(ref User user) { if (user == null) user = new User(); }

Andrei Rinea
Nice answer. I also think you've found a defect in the markdown, as your code isn't displaying as code.
ck
yep after listing the code does not format correctly even if there are paragraphs above ...
Thank you. However it may be my fault for not properly indenting the code. I'll try an edit.
Andrei Rinea
Tried edit... code formatting still doesn't work
Andrei Rinea
Turns out I'm not the only one having problems with code and lists : http://stackoverflow.uservoice.com/pages/1722-general/suggestions/70800-code-formatting-and-lists
Andrei Rinea
+1  A: 

You also need to take into account value and reference types. When passing a reference type to a method as a parameter, you pass the pointer to the variable. This means that inside the method you can make changes to the variable and they will be available to the code that called the method, however if you set it to null, you are only setting the pointer to null and the variable will be intact when your method returns.

ck