Click here to Skip to main content
15,904,297 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Good day all!!!

I have a DataTable that I'm looping through:

C#
foreach (DataRow r in table.Rows)
{
}


I also have a class that inherits DataRow:

C#
public class OutlookDataRow : System.Data.DataRow
{
    public OutlookGridRow OutlookRow { get; set }

    public OutlookDataRow(System.Data.DataRowBuilder builder)
       : base(builder)
    {
    }
}


How would I go about casting DataRow r to OutlookDataRow as it loops through the DataTable???

Doing any of the follow throws a casting error:

C#
OutlookDataRow dr = r;

OutlookDataRow dr = (OutlookDataRow)r;

OutlookDataRow dr = r as OutlookDataRow;

foreach (OutlookDataRow r in table.Rows)
{
}
Posted

1 solution

You can't - you cannot cast "up" the inheritance tree as the system would have to "invent" information for new items in the derived class. Since it doesn't have a clue what you added or what you want to do with it, it won't even try.

The best solution is probably to define a constructor for your derived class which takes a DataRow as the parameter and constructs a new OutlookDataRow based on that information.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900