Finished Testing Object Reference & Referencing Different Object & Passing Parameter by Refernce

Jason Zhu 2021-02-18 15:58:58 +11:00
parent 1851eed7fc
commit aba007ccef

@ -21,7 +21,7 @@ Steps:
Convention of naming:
* Public class member beginning with UpperCase
## Testing Object References & Referencing Different Object
## Testing Object References & Referencing Different Object & Passing Parameters by Reference
Two reference type variable can reference 2 different or same object.
@ -29,3 +29,53 @@ Check tests `GetBookReturnDifferentObject()` & `TwoVarsCanReferenceSameObject()`
Trick:
* `Object.ReferenceEquals(obj1, obj2)` return Boolean for whether two objs has same reference value
## Passing Parameters by Value & Returning Object References
Reference:
* [Passing Parameter (C# Programming Guide)](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-parameters)
**Passing a value-type variable to a method by value** means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no effect on the original data stored in the argument variable. If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword.
```csharp
[Fact]
public void CSharpIsPassByValue()
{
var book1 = GetBook("Book1");
GetBookSetName(book1, "New Name");
Assert.Equal(book1.Name, "New Name");
}
private void GetBookSetName(Book book, string name)
{
book = new Book(name);
book.Name = name;
}
```
As shown in above:
1. `boo1` is pass-by-value into function (i.e. its value, reference to object is copied into function)
2. In `GetBookSetName` function, that value (reference to "Book1" object) is replaced with a new object.
3. `book.Name = name` only update name within function. Nothing reflect on object itself.
To **Pass-parameter-by-reference**, use `ref/out param` in both function definition and invoking
```csharp
[Fact]
public void CSharpCanPassByReference()
{
var book1 = GetBook("Book1");
GetBookSetName(ref book1, "New Name");
Assert.Equal(book1.Name, "New Name");
}
private void GetBookSetName(ref Book book, string name)
{
book = new Book(name);
book.Name = name;
}
```
Not very often use.