Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast object to type without creating new variable

This question is a curiosity of mine, so I'm not look for a away around this just an explanation.

I've been wondering why a new variable has to be created when you are casting.

It's the sort of thing I would have thought the compiler could work it's magic on as I am casting to a known type.

So that code like this could be written shorter.

DataTable dataTable = RetrieveDataTableFrom(whereEver);

foreach (DataRow row in dataTable.rows)
{
    if (row.ItemArray[0].GetType() == typeof(myTypeA))
    {
         MyTypeA myTypeA = (myTypeA)row.ItemArray[0];
         myTypeA.myCustomProperty = "dem works";
    }
}

Like this, where I just edit the property more directly.

foreach (DataRow row in dataTable.rows)
{
    if (row.ItemArray[0].GetType() == typeof(myTypeA))
    {
         (myTypeA)row.ItemArray[0].myCustomProperty = "dem breaks";
    }
}

Edit: Oh so a mistake in my understanding! Whoops, I thought it didn't make sense... ha. A little extra, would you consider either method (assuming correct amount of parentheses used) more clear/readable than the other?

like image 795
Amicable Avatar asked Feb 18 '23 04:02

Amicable


1 Answers

This should work

foreach (DataRow row in dataTable.rows)
{
    if (row.ItemArray[0].GetType() == typeof(myTypeA))
    {
         ((myTypeA)row.ItemArray[0]).myCustomProperty = "dem breaks";
    }
}

or you can use LINQ

foreach (var row in dataTable.Rows.Cast<DataRow>().Where(row => row.ItemArray[0].GetType() == typeof(myTypeA)))
{
   ((myTypeA)row.ItemArray[0]).myCustomProperty = "dem breaks";
}
like image 133
Ivan Salo Avatar answered Feb 21 '23 03:02

Ivan Salo