Let’s say I have a DataTable with five columns. I am curious as to why the following works:
dt.Columns.Add("Blah").SetOrdinal(5);
But the following throws an ArgumentOutOfRangeException:
dt.Columns.Add("Blah").SetOrdinal(dt.Columns.Count);
I also tried
dt.Columns.Add("Blah").SetOrdinal(dt.Columns.Count - 1);
which works, but I’m not entirely sure why. Does it have something to do with the column being added before the SetOrdinal is executed, thus increasing the count beyond the range of columns?
“Does it have something to do with the column being added before the SetOrdinal is executed”
Yes.
At the time the last part is evaluated:
dt.Columns.Count == 6. Generally speaking you should avoid compound statements that reference something that changes in the same statement. Although the evaluation order is predictable it’s not especially intuitive — you’ll end up making mistakes. This is better:
or even better:
Don’t try to make your code shorter just for the sake of making it shorter. If saving a few characters (which really means nothing in compiled code) makes the intent less clear, then it’s definitely not worth it.