0

I've extended the DataTable class as follows:

class DataTableExtended:DataTable
    {
        public void specialMethod()
        {}
    }

I want to parse an XML node into this child class, which I tried to do with the following:

public DataTableExtended parseNodeToDataTable()
        {
            DataSet ds = new DataSet();
            XmlNodeReader reader = new XmlNodeReader(this.resultNodes);
            ds.ReadXml(reader);
            DataTable dt = ds.Tables[1];
            DataTableExtended dte=(DataTableExtended) dt;
            return dt;
        }

It's throwing an InvalidCastException. From what I've read so far, this is because it's not possible to cast a parent class to a child class. Is that accurate? If so, I know I can rewrite the DataTableExtended constructor so that it accepts a DataTable argument and copies that table's information, but I was hoping that there's a more direct way of doing this.

sigil
  • 9,370
  • 40
  • 119
  • 199

2 Answers2

2

I would write an extension method for DataTable instead of subclassing it

public static class DataTableExtensions
{
    public static void SpecialMethod(this DataTable dt)
    {
        //do something
    }
}

--

DataTable dt = .........
dt.SpecialMethod();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

I like to read the : operator as is a. So a DataTableExtended is a DataTable. Note that this does not imply that a DataTable is a DataTableExtended, hence the failure to cast.

I think the best way of "casting" in this direction is to take an instance of the base class in your constructor, as you suggest.

Also see this answer.

Community
  • 1
  • 1
RichardTowers
  • 4,682
  • 1
  • 26
  • 43