Can I modify a passed method parameter

后端 未结 3 1973
逝去的感伤
逝去的感伤 2020-12-06 18:07

my gut feeling says I shouldn\'t do the following. I don\'t get any warnings about it.

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


        
3条回答
  •  醉话见心
    2020-12-06 18:18

    You can change it but the change will not go back to the caller.

    If it is a ValueType -> The copy of object is sent

    If it is a RefernceType -> Copy of Object reference will be sent by value. In this way properties of the object can be changed but not the reference itself - caller will not see the change anyway.

    If it is sent ref -> Reference can be changed.

    In C++ you can use const to prevent the change but C# does not have that. This is only to prevent the programmer by mistake try to change it - depending where the const is used.

提交回复
热议问题