■
Source Code
The ValueAndReferenceTypes project is located under the Chapter 4 subdirectory.
Passing Reference Types by Value
Reference types or value types can obviously be passed as parameters to type members. However,
passing a reference type (e.g., a class) by reference is quite different from passing it by value. To
understand the distinction, assume you have a simple Person class defined in a new Console Appli-
cation project named RefTypeValTypeParams, defined as follows:
class Person
{
public string personName;
public int personAge;
// Constructors.
public Person(string name, int age)
{
personName = name;
personAge = age;
}
public Person(){}
public void Display()
{
Console.WriteLine("Name: {0}, Age: {1}", personName, personAge);
}
}
Now, what if you create a method that allows the caller to send in the Person type by value
(note the lack of parameter modifiers):
C H A P T E R 4
■
C O R E C # P R O G R A M M I N G C O N S T R U C T S, PA RT I I
133
8849CH04.qxd 10/1/07 10:31 AM Page 133
static void SendAPersonByValue(Person p)
{
Do'stlaringiz bilan baham: |