C# Passing arguments by default is ByRef instead of ByVal

后端 未结 5 1846
闹比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:10

    Ran across this and thought I should share what Microsoft says:

    "Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference."

    MSDN: ref (C# Reference)

    0 讨论(0)
  • 2020-12-05 08:13

    You need to learn the difference between reference types and value types. Here I presume you are using a reference type License, which means you are actually parsing a reference to the instance in question.

    See: http://msdn.microsoft.com/en-us/library/aa711899(v=vs.71).aspx

    Although, not necessarily correct a value type is often allocated on the stack or within a reference type. While reference types are always allocated on the managed heap.

    0 讨论(0)
  • 2020-12-05 08:13

    When passing license in InsertLicense you pass it not by value but as reference. That means when changing the registered item to true, it will change that and after returning the reference the registered item will be true.

    0 讨论(0)
  • 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)
    0 讨论(0)
  • 2020-12-05 08:26

    You are passing the licence argument by value; essentially this means you can modify any public properties of the object. However, if you reassign the reference of the licence object to a new object, i.e. if you did this:

    public static void InsertLicense(License license)      
    {         
       license = new Licence();         
       UpdateLicense(license);      
    }
    

    the caller won't reference the new license object defined in the static method unless you passed it by ref.

    Remember that all parameters are passed into methods by value unless you use the ref or out keywords.

    0 讨论(0)
提交回复
热议问题