There are two methods to pass a parameter to a method: pass by value and pass by reference. Passing by value will cause the called method to have its own private copy of this parameter. If the parameter is of the value type, the called method will have its own private copy of the instance. If the parameter is of the reference type, the called method has a private copy of the reference type. Passing by reference is a method parameter modified by ref or out in C #. Passing by reference leads to a managed pointer for the called method, which points to the variable of the caller. I will not talk much about it. It is something that everyone is familiar. Below is a small demo to visualize these concepts.
Public class Book
{
Public
String BookName {get;
Set ;}
Public
String Author {get;
Set ;}
Public
Double Price {get;
Set ;}
}
Public static string
GetInfos (Book book, int
Count)
{
Return
String. Format ("BookName: {0}, Author: {1}, Price: {2}
And Count: {3 }",
Book. BookName, book. Author, book. Price, count );
}
Public static string
ChangeInfos (ref Book
Book, ref int
Count)
{
Book = new
Book
{
BookName = "CLR Via C #",
Author = "Jeffrey Richter ",
Price = 68.00
};
Count = 10;
Return
String. Format ("BookName: {0}, Author: {1}, Price: {2}
And Count: {3 }",
Book. BookName, book. Author, book. Price, count );
}
Static void Main (string []
Args)
{
Book
Book = new Book
{
BookName = "Essential. Net ",
Author = "Don
Box ",
Price = 48.00
};
Int
N = 5;
Console. writeline (getinfos (book,
N ));
Console. writeline ("-------------------------------------------------------------");
Console. writeline (changeinfos (ref book, ref n ));
Console. writeline ("-------------------------------------------------------------");
Console. WriteLine (GetInfos (book,
N ));
Console. ReadLine ();
}
When GetInfos is called, the value-based transmission mode is used. book is the reference type, and n is the value type. Parameter transfer:
When ChangeInfos is called, both parameters of ChangeInfos are passed by reference. The saved address points to two variables in the Main method. After ChangeInfos modifies the two parameters
Program running result: