I'm learning C# and understand a class as a recipe and an instance as an object made from it. Course material says the runtime performs a lookup when I use an object reference. What is actually being looked up?
What does it mean that .NET gives you the illusion of accessing an object directly?
Answers
For a class instance, a variable usually holds a reference to the object, not the whole object itself. Think of the reference as a way to find the object. When you write dice.Next(), C# lets you use that reference to call a method on the object.
If you assign dice to another variable, both variables can refer to the same object. Changing the object through one reference is then visible through the other. Assigning a different reference to one variable does not change the other variable.
Reply to this answer
The word lookup can make this sound more mysterious than it is. It does not necessarily mean the runtime searches a table every time you use a variable. A managed reference normally lets generated code locate the object in memory.
The garbage collector can move objects and update live references as needed. You generally don't have to manage those addresses yourself. The exact mechanics are implementation details, so it is better not to assume a particular lookup or locking mechanism.
Reply to this answer
I wouldn't worry too much about the word illusion. Using a reference is the normal way to work with a class object in C#. The dot syntax does the work of accessing the object for you, so you don't need to learn C pointers to understand this.
Reply to this answer
One distinction worth keeping in mind: this explanation is about reference types, such as classes. C# also has value types, such as int and structs. A variable of a value type holds its value, so assigning it to another variable normally copies that value rather than making a second reference to the same object.
Reply to this answer
Add your answer
Answers are reviewed before publication.
2v+hingepin_740:
So if dice refers to a Random instance, Random is the class and the instance is the particular object?
b.603+rainboot:
Yes. You can create multiple Random instances, and each one is a separate object. Multiple references can also point to the same instance.