Reputation: 391
I have two classes named Road and City, they have the following methods:
"class Road"
public Road()
{
public int getId()
{
return this.id;
}
}
"class City"
public City()
{
public string getName()
{
return this.name;
}
}
In another class named Image, I create instances of City and Road of the type Object
Example
Object o = new Object();
City c = cc.getCityByCoordinates(coordinates);
o = c;
Now how can I access the methods from City.class on the "o" object? Like o.getName(); - If that is even possible, please help.
Upvotes: 0
Views: 167
Reputation: 673
You can also use reflection to retrieve the result off of City.
MethodInfo mi = c.GetType().GetMethod("getName");
var result = mi.Invoke(o, null).ToString()
Upvotes: 0
Reputation: 866
City cityFromObject = o as City;
if(null != cityFromObject) {
// do something with cityFromObject.getName();
}
Upvotes: 1
Reputation: 61349
You can easily do this by casting to "City":
City c = o as City;
c.getName();
Note that the as
operator will return null if the cast is invalid, so you should check before using it:
City c = o as City;
if (c != null)
c.getName();
The other way is to use the is
operator and a C-style cast:
if (o is City)
((City)o).getName();
A word of warning, downcasting like this is a "code smell". Look at your code and see why you need to do this. Perhaps it should be stored in an interface instead. Object
variables can also be a "code smell", and used only if necessary.
Upvotes: 5
Reputation: 152556
How can I access the methods from
City
class on the "o" object?
Cast it:
Object o = new Object();
City c = cc.getCityByCoordinates(coordinates);
o = c;
string name = ((City)o).getName();
If o
is not really a City
then you'll get an exception at run-time. To check if o
is a City
before trying to cast it, you can use as
:
City c2 = o as City; // c2 will be `null` if o is not castable to City
if(c2 != null)
string name = c2.getName();
Upvotes: 3