Do you need a ref or out parameter?

I am passing an instance of the class to a method, and this method will change the instance.

Do I need to use the out or ref keyword, since this is the class I'm going through?

This is what I want to do:

public void Blah() { Blah b = Dao.GetBlah(23); SomeService.ModifyXml(b); // do I need to use out or ref here? Dao.SaveXml(b.xml); } 
+2
source share
5 answers

The right way to think about this is to use ref / out if you want to create an alias for the variable . That is, when you say:

 void M(ref int x) { x = 10; } ... int q = 123; M(ref q); 

what do you say: "x is another name for the q variable." Any changes in the content for x changes q and any changes in the contents of q change x, since x and q are just two names for the same storage location.

Note that this is completely different from two variables related to the same object:

 object y = "hello"; object z = y; 

Here we have two variables, each variable has one name, each variable refers to one object, and two variables refer to the same object. In the previous example, we have only one variable with two names.

It is clear?

+14
source

If the reference b does not change, and only the properties of b change, you do not need either ref or out . Both of them will be used only if the link itself is changed.

I expanded your sample code a bit to include use for ref , out , and also:

http://pastebin.ca/1749793

[Snip]

 public void Run() { Blah b = Dao.GetBlah(23); SomeService.ModifyXml(b); // do I need to use out or ref here? Dao.SaveXml(b.Xml); SomeService.SubstituteNew(out b); Dao.SaveXml(b.Xml); SomeService.ReadThenReplace(ref b); Dao.SaveXml(b.Xml); } 

The rest of the code is in this PasteBin.

+5
source

No, you do not want to return or go here. You want to use ref when the method changes the object this parameter points to. You want to use when the method will always indicate a new object to indicate the parameter.

+1
source

No no. The default behavior when passing an instance of a reference type as a parameter is passing its reference by value. This means that you can change the current instance, but not change it for another different instance. If this is what you mean by instance modification, then you do not need ref or out .

+1
source

An easy way to check with intellisense is to hover over ModifyXml , and if the parameter in the method signature contains out , for example ModifyXml( out Blah blah ) , you need the out keyword. The same goes for ref .

0
source

All Articles