Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
DotNETFrameworkNotesForProfessionals.pdf
Скачиваний:
32
Добавлен:
20.05.2023
Размер:
1.82 Mб
Скачать

Chapter 12: Custom Types

Section 12.1: Struct Definition

Structs inherit from System.ValueType, are value types, and live on the stack. When value types are passed as a parameter, they are passed by value.

Struct MyStruct

{

public int x; public int y;

}

Passed by value means that the value of the parameter is copied for the method, and any changes made to the parameter in the method are not reflected outside of the method. For instance, consider the following code, which calls a method named AddNumbers, passing in the variables a and b, which are of type int, which is a Value type.

int a = 5; int b = 6;

AddNumbers(a,b);

public AddNumbers(int x, int y)

{

int

z =

x + y; // z becomes 11

x

=

x

+

5;

//

now

we changed x

to be 10

z

=

x

+

y;

//

now

z becomes 16

 

}

Even though we added 5 to x inside the method, the value of a remains unchanged, because it's a Value type, and that means x was a copy of a's value, but not actually a.

Remember, Value types live on the stack, and are passed by value.

Section 12.2: Class Definition

Classes inherit from System.Object, are reference types, and live on the heap. When reference types are passed as a parameter, they are passed by reference.

public Class MyClass

{

public int a; public int b;

}

Passed by reference means that a reference to the parameter is passed to the method, and any changes to the parameter will be reflected outside of the method when it returns, because the reference is to the exact same object in memory. Let's use the same example as before, but we'll "wrap" the ints in a class first.

MyClass instanceOfMyClass = new MyClass(); instanceOfMyClass.a = 5; instanceOfMyClass.b = 6;

AddNumbers(instanceOfMyClass);

public AddNumbers(MyClass sample)

{

GoalKicker.com – .NET Framework Notes for Professionals

54

int z = sample.a + sample.b; // z becomes 11 sample.a = sample.a + 5; // now we changed a to be 10 z = sample.a + sample.b; // now z becomes 16

}

This time, when we changed sample.a to 10, the value of instanceOfMyClass.a also changes, because it was passed by reference. Passed by reference means that a reference (also sometimes called a pointer) to the object was passed into the method, instead of a copy of the object itself.

Remember, Reference types live on the heap, and are passed by reference.

GoalKicker.com – .NET Framework Notes for Professionals

55