1

I have:

public class Element : XmlElement
{
  // there is constructor, not important

  public string ElementSomething {get;set;}

}

public class Cat: Element {
  // there is constructor, not important

  public string CatSomething {get;set;}

}

And now an epic question:

public void SomeMethod()
{
  XmlElement xmlelem = new XmlElement (/*some params, not important */);
  Element elem = new Element (/*some params, not important*/);
  elem.ElementSomething = "Element";
  Cat catelem = new Cat(/*some params, not important*/);
  catelem .CatSomething = "Cat";  
}

How to cast elem to Cat and back?

Cat newcat = elem as Cat;

don't work.

meridian
  • 407
  • 6
  • 11

2 Answers2

4

You can't - because it's not a Cat. This has nothing to do with XML at all - it's basic C#. You're trying to do the equivalent of:

object x = new Button();
string s = x as string;

What would you expect the content of s to be, if this worked?

You can't cast an object reference to a type which the object simply isn't an instance of. You could potentially write a conversion method to create a new object... but a better approach is usually to use composition rather than inheritance in the first place.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You cannot cast a parent into a child class. See also this question: Unable to Cast from Parent Class to Child Class

The other way around is easy:

 Cat cat = new Cat(...);
 var element = cat as Element;
Community
  • 1
  • 1
ChrisWue
  • 18,612
  • 4
  • 58
  • 83