Cast Object

  • Thread starter Thread starter lil J
  • Start date Start date
L

lil J

lets say i 2Classes

class Person{
string surname;
}

class House{
string street;
}


I have an Object, but it's Type can be Person or House . I want to Cast
this Object to its orign.

//current.GetType() -> Person
Object current;


//Not Working
((current.GetType)current.surname).name;
 
that's clear, but if it's House?

Object current can change at runtime

Marc said:
((Person)current).surname
lets say i 2Classes

class Person{
string surname;
}

class House{
string street;
}


I have an Object, but it's Type can be Person or House . I want to Cast
this Object to its orign.

//current.GetType() -> Person
Object current;


//Not Working
((current.GetType)current.surname).name;
 
that's clear, but if it's House?

Object current can change at runtime

But at that point, current.surname wouldn't be valid anyway.

Casts are there to tell the *compiler* that something must be of a
certain type (checked at runtime, of course). If you need the compiler
to know the type, that's almost always because you want to use some
member of that type - in which case, you should know the type that the
member belongs to.

If you have several types with common members in, encapsulate those
members in an interface, make all the types implement that interface,
and then cast to the interface instead.

Jon
 
Or in your simple example use "as" to cast your object

Object houseOrPerson; //your Object

Person person = houseOrPerson as Person;
if (person != null)
//do something
else
//your houseOrPerson was a house ;)
 
I would agree with Jon that interfaces or polymorphism would be a
better solution here - but I maintain that my first post answered the
question as asked ;-p

If the question specifically relates to the *most common* textual
representation of the item, then polymorphism with ToString() would be
a valid option. If it is something more complex then an interface or
base-class comes into play; ToString() example (tidied a bit):

class Person {
private string surname = "";
[DefaultValue("")]
public string Surname { get { return surname; } set { surname
= value; } }
public override string ToString() {
return Surname;
}
}

class House {
private string street = "";
[DefaultValue("")]
public string Street { get { return street; } set { street =
value; } }
public override string ToString() {
return Street; // questionable as a ToString..
}
}

// blah
string caption = object.ToString();
 
Back
Top