How can I access the objects property in this situation?
Araba araba = new Araba();
araba.Renk = "mavi";
araba.fiyat = 12345;
// I created this class and it working normally
ArrayTypedStack asd = new ArrayTypedStack(10);
asd.Push(araba);
object araba2 = asd.Pop();
araba2. //cant access
CodePudding user response:
Here you are assigning the value of asd.Pop()
to a variable of the type object
.
object
is the root of all objects (all objects inherit from it and can be casted to it) and as such has no real information about what it is. It's just like any object in real life is a thing
.
The solution here is to declare the araba2
as the type Araba
, that will give you access to all the properties on the next line.
I don't know the implementation of the ArrayTypedStack
and what the Pop()
method looks like (it's return type) so it's possible that this will give you an error, saying that it can't convert an object to the type Araba. This is the type safety implemented in .NET. You have to convince .NET that it's of the type Araba
, this can be by casting
Araba araba2 = (Araba)asd.Pop();
this can still give an error on runtime if the object returned from Pop()
isn't of the type Araba
, in this case you can ask .NET to try to cast it, there are serveral options for this:
object popResult = asd.Pop();
if (popResult is Araba) {
Araba araba2 = (Araba)popResult;
}
// can be written as follows:
if (popResult is Araba araba3) {
araba3.fiyat = 65432;
}
// can also be done as follows
Araba araba4 = asd.Pop() as Araba;
if (araba4 != null) {
araba4.fiyat = 84368;
}
CodePudding user response:
Well, your araba2 variable is of type object
. Thus, regardless of the actual type of the instance it contains, through the object
variable araba2 you can only access members that are provided by the type object
.
To access members provided by the Araba
type (and assuming the instance in the araba2 variable is an instance of type Araba
), the araba2 variable itself should be of type Araba
, or the value of araba2 needs to be cast as Araba
.
Thus,
var araba2 = asd.Pop();
or
var araba2 = (Araba) asd.Pop();
with the first example code line above requiring that the return type of the Pop method is Araba
(or a type derived from Araba
). The latter code line example will work regardless of the return type of Pop as long as the value returned by Pop is an actual Araba
instance (or is something that is convertible to an Araba
instance).