Casting in and out

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is it possible to force a cast to an inherited class?

class Program
{
static void Main(string [] args)
{
Father Dad = new Father( );
Son boy = (Son) Dad; // <<== fails at run time with
invalid cast
}
class Father { }
class Son : Father { }
}

Is there any way to allow the son to follow in his father's footsteps...
 
public class Father
{
string m_Name;

public string Name
{
get
{
return this.m_Name;
}

set
{

this.m_Name = value;
}

}
}

public class Son : Father

{

....

}
 
Paulustrious said:
Is it possible to force a cast to an inherited class?

Unless one of the classes involved explicitly knows how to do it (eg
Father has a ToSon method, or Son has a constructor taking a Father)
then no. Even then, it would be a case of building a new object. You
can't tell the system that something of one type is actually of a more
derived type.

Can you give a more concrete example of why you want to do this? There
may well be a different idiom which would be useful for you.

Jon
 
Paulustrious said:
Is it possible to force a cast to an inherited class?

Is there any way to allow the son to follow in his father's
footsteps...

Do you need the object cast as a different object? Or can you simply use
properties?

// Using VS2005.
class Person
{
private string m_Name = String.Empty;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
}

class PersonCollection : List<Person> {}

class FamilyMember : Person
{
private Person m_Father = new Person();
public Person Father
{
get { return m_Father; }
set { m_Father = value; }
}

private PersonCollection m_Sons = new PersonCollection();
public PersonCollection Sons
{
get { return m_Sons; }
set { m_Sons = value; }
}
}
 
Thanks you for your reply. What I hadn't realised was the runtime checking of
casting operations. I was used to 'unsafe' casting wher it was down to the
coder to ensure type-safe operations. It highlighted a structural error in
what I was coding. I understood once I realised that the following worked.

class Program
{
static void Main(string [] args)
{
Egg egg = new Egg ( );
Chicken chicken = egg;
egg = (Egg)chicken;
}
class Chicken { }
class Egg : Chicken { }
}

Thanks for your help..
(To quote Arnold ... I'll be back)
 
How very strange - I was writing a template collection class and you seem to
have foreseen that. It was a normal tree but with some specilized additions.

As I said earlier / elsewhere I was structuring my creations wrongly.

class FamilyMember<T> where T : new()
{
FamilyMember<T> Parent.....get set
FamilyMember<T> [] Children... get set
T Data .... get set

public AddChild( T pData) ...and so on
}
class Food {}
class FoodMember : FamilyMember<T>
{}

I was adding Children in the form of FamilyMember<T> and trying to retrieve
them as a FoodMember...or something like that.

Sorry to have wasted people's time

Regards - Paul whoisat PaulCotter.com
 
Back
Top