Can I change the parameter of the past method

My gut feeling says I should not do the following. I do not receive any warnings about this.

void test(DateTime d) { d = d.AddDays(2); //do some thing with d } 

or is it more true

  void test(DateTime d) { DateTime _d = d.AddDays(1); //do some thing with _d } 

For some reason, I always handled the passed parameters, as in the second example. But I'm not sure if this is really ... maybe it's just neon code.

I do not think that the calling method will use the changed value. who have any opinions

+7
c #
source share
3 answers

Changes to a parameter value are invisible to the caller, unless it is a ref or out parameter.

This is not the case if you make a change to the object of the reference type that the parameter refers to. For example:

 public void Foo(StringBuilder b) { // Changes the value of the parameter (b) - not seen by caller b = new StringBuilder(); } public void Bar(StringBuilder b) { // Changes the contents of the StringBuilder referred to by b value - // this will be seen by the caller b.Append("Hello"); } 

Finally, if the parameter is passed by reference, this change is visible:

 public void Baz(ref StringBuilder b) { // This change *will* be seen b = new StringBuilder(); } 

For more information, see the article on parameter passing .

+14
source share

You can change it, but the change will not return to the caller.

If it is ValueType -> copy object is sent

If this value is RefernceTypeCopy object references, will be sent by value. Thus, the properties of the object can be changed, but not the links themselves - the calling object will still not see the changes.

If sent ref → Link may be changed.

In C ++, you can use const to prevent change, but C # does not. This is only for the programmer to mistakenly try to change it - depending on where the const used.

+4
source share

If you want to have access to the original value, use the second method.

If you don't care about the original value, you can use one of them (I would probably still use the second option).

In any case, you will not harm other values ​​(even if you reassigned the value, in this case it will not return to the caller).

0
source share

All Articles