accessing an instance of a class in another class
How do you access an instance of a class variable or method if you need to access it from another class? I created the instance in the main program. Do I have to pass it all as arguments and then assign it to another instance of the class created in the method of the other class or is there a better way?
11 Replies
you need a reference to the instance in question
Something somewhere must be aware of both instances and be able to pass one to the other, or otherwise exposing them to eachother
Could you show us what you have tried ?
This is the Program.cs
Car.cs Class
Race.cs Class where I'm having issues. And I know I can't say playerCar.DrawCar() cause it's an instance from Program.CS. Just trying to figure out the best way to pass it over.
Finally, though it's not really important to the discussion Start.cs
You can pass the car to the
Race
class via a constructor, or you can pass it to the DrawTrack()
method directlyas an argument? Would you then have to copy it into a new instance of the Car Class inside that Race Class or can you just access the instances directly from the arguments passed in?
Sorry, I still find the class thing a little confusing so I want to get it right. and thanks for your help.
Classes are "pass by reference", meaning if you pass it in and store it as a variable inside the race, its just a reference pointing to the same car
I would recommend you use
Console.ReadKey().Key
instead of Console.ReadKey().KeyChar
. It gives you a nice enum
to deal with rather than char
As for your issue about using classes from other classes, a quick glance at your code makes me think you should move the declaration of the car objects from Program
into Race
before
after
but there are usually numerous ways to handle any given topic in code, so just passing a reference as was mentioned works tooOk so kind of like a pointer?
exactly like a pointer
ah ok. Thanks all
So like this right? It seems to work so I assume it's right
Yup