.NET Parameter passing - by reference v/s by value

后端 未结 6 1066
抹茶落季
抹茶落季 2020-12-15 06:05

I\'m trying to validate my understanding of how C#/.NET/CLR treats value types and reference types. I\'ve read so many contradicting explanations I stil

This is what

6条回答
  •  青春惊慌失措
    2020-12-15 06:49

    The term "pass by value" is a little misleading.

    There are two things you are doing:

    1) passing a reference type (Person p) as a parameter to a method

    2) setting a refence type variable (Person p2) to an already existing variable (Person p)

    Let's look at each case.

    Case 1

    You created Person p pointing to a location in memory, let's call this location x. When you go into method AppendWithUnderScore, you run the following code:

    p.Name = p.Name + "_"; 
    

    The method call creates a new local variable p, that points to the same location in memory: x. So, if you modify p inside your method, you will change the state of p.

    However, inside this method, if you set p = null, then you will not null out the p outside the method. This behavior is called "pass by value"

    Case 2

    This case is similar to the above case, but slightly different. When you create a new variable p2 = p, you are simply saying that p2 references the object at the location of p. So now if you modify p2, you are modifying p since they reference the same object. If you now say p2 = null, then p will now also be null. Note the difference between this behavior and the behavior inside the method call. That behavioral difference outlines how "pass by value" works when calling methods

提交回复
热议问题