I am just starting out with OOP and trying to understand the code below. Why is book2 object changing its value even though i am not defining it to something els just using that object to define the values of the objects in books array.
Book[] books = new Book[5];
Book book2 = new Book("test", "test1", 800);
for (int i = 0; i < books.Length; i )
{
books[i] = book2;
Console.WriteLine(books[i].pages);
books[i].pages = 10;
}
Is there something fundemental i have missed about objects? In my thinking this code should return 800, 5 times.
Just and explination how my thinking is flawed
CodePudding user response:
You are assigning the same object reference to all positions in the array. So the Page = 10 that you are doing is being done always on the same object.
That is why you see 800, 810, 820 etc.
CodePudding user response:
In C# there are two types of objects in terms of memory representation, with the terms "value type" and "reference type".
Value types hold their value by instance, and this type is underlying most simple types (integral numeric types, floating-point numeric types, bool and char)
Reference types are (simplified) "anything else". Precisely said, definied by using any of these keywords: class, interface, delegate, record, dynamic. Also the build-in types object, dynamic and string are reference types.
The reason for this difference can be abbreviated by performance. While it is quite efficient to store the data bits of number, for complex objects instead a reference is used, which can be thought of as the "number of the memory register" used to store the main data. This "register number" can be handled quite effiently.
As you defined class Book {...}
, you created a reference type variable. Your for-loop is assigning each books[] item the "value" book2, they all are initialized to point to the same piece of memory. Thus modifying one of these instances will in turn modify modify all of them.
If you need independent instances, then you have assign a value including the new keyword, like fabian showed earlier. Eventually you will find that having a "copy constructor" can be quite handy (like in var anotherBook = new Book(existingBook);
)
CodePudding user response:
For that Book are reference type and books[i] vs book2 referenced are same which value storage on heap for example books[i]-->object(on the heap) and books-->object (on the heap) that values are same.That is why the value respectiveliy output as 800,810,820,830,840