M B

M B

  • NA
  • 5
  • 0

Cast Inherited to Base

May 19 2010 3:42 PM

This question applies to VB.net and C# so I posted it here in the hope I will get more answers. However, the code will be presented in VB.net. Feel free to respond in C#
The program bellow trhows an error in the line "mTable2 = mTable.Copy". The error is: "Unable to cast object of type 'System.Data.DataTable' to type 'InherintanceQuestion.InheritedTable". This is because mTables is an instance of the InheritedTable class which inherits a DataTable and mTable is a DataTable. So, is there any way I can create the mTable2 to the mTable.copy to the mTable.
 

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim mTable As New DataTable
        Dim mTable2 As New InheritedTable
        mTable.Columns.Add("Col1", System.Type.GetType("System.String"))
        mTable.Columns.Add("Col2", System.Type.GetType("System.String"))
        Dim Row As DataRow = mTable.NewRow
        Row(0) = "A" : Row(1) = "B" : mTable.Rows.Add(Row)
        Row = mTable.NewRow
        Row(0) = "C" : Row(1) = "D" : mTable.Rows.Add(Row)
        mTable2 = CType(mTable.Clone, InheritedTable).Copy 'THE ERROR OCCURS HERE
    End Sub

End Class

 

 
Public Class InheritedTable
    Inherits System.Data.DataTable
    Private Sub DoSomething()
        'Any code.
    End Sub
End Class

Attachment: QuestionCode.zip

Answers (1)