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?
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With