Maurice Klimek
Maurice Klimek

Reputation: 1092

Converting DataTable objects to custom class objects inheriting from DataTable

I want to create a class that will add some new methods helpful in using a DataTable class. I want to avoid static classes, so I created a class

MyDataTable : DataTable

and my methods there.

How can I convert DataTable objects to MyDataTable objects? I already tried

MyDataTable dt2 = (MyDataTable)dt;

But it returns a InvalidCastException.

I know now that it doesn't work this way. But I also have no idea how can I solve this. Can anyone help me with this?

Upvotes: 0

Views: 1248

Answers (2)

Kishore Kumar
Kishore Kumar

Reputation: 12874

You can even write implicit cast for your Custom Class inherited from DataTable.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

Of course it causes an InvalidCastException since not every DataTable is of type MyDataTable. You need to create an instance of your type:

MyDataTable myTable = new MyDataTable();

Normally i provide the most used constructors of the type i'm inheriting from. You can call the base constructor from the constructor of your type. So for example:

public class MyDataTable : DataTable
{
    public MyDataTable(string name)
        : base(name)
    {
        // additional initialization
    }
}

Upvotes: 2

Related Questions