Зміст курсу
C# Beyond Basics
C# Beyond Basics
Class Objects vs Struct Objects
Class objects can also be stored in Arrays, Dictionaries and Lists just like structs however it is important to note that class objects are passed by reference while struct objects are passed by value.
This concept is important because passing simple values like int
, float
or double
into methods is different from passing complex objects and structures into methods. Let's look at an example to understand this concept better.
We will create a simple struct object and pass it into a method. We will change its value from inside the method and see what happens to the value of the original object:
index
The output shows that the value of passedObject
was updated while the value of originalObject
remained unchanged. This shows that when we pass a struct object into a method, a duplicate of that object is created and passed into the method, or in other words, it is passed by value.
Now let's use the exact same code, only changing the term struct
to class
:
index
You'll notice that the output has changed - both the passedObject
and the originalObject
have the same value this time. This proves that when we pass a class object into a method, it passes a reference to the original object into the method, making changes to passedObject
changes originalObject
.
This property also applies when assigning objects to variables. Following is an example that shows the behavior of a struct object:
index
The same code but this time for a class object:
index
Все було зрозуміло?