C# Passing arguments by default is ByRef instead of ByVal

后端 未结 5 1866
闹比i
闹比i 2020-12-05 07:40

I know the default is ByVal in C#. I used same variable names in many places and then I noticed passed values change and come back. I think I knew scope mechanism of C# wron

5条回答
  •  长情又很酷
    2020-12-05 08:18

    The argument is being passed by value - but the argument isn't an object, it's a reference. That reference is being passed by value, but any changes made to the object via that reference will still be seen by the caller.

    This is very different to real pass by reference, where changes to the parameter itself such as this:

     public static void InsertLicense(ref License license)
     {
        // Change to the parameter itself, not the object it refers to!
        license = null;
     }
    

    Now if you call InsertLicense(ref foo), it will make foo null afterwards. Without the ref, it wouldn't.

    For more information, see two articles I've written:

    • Parameter passing in C#
    • References and values (the differences between value types and reference types)

提交回复
热议问题