Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding columns to a DataTable using SetOrdinal

Tags:

c#

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?

like image 230
Sid Holland Avatar asked Aug 13 '26 18:08

Sid Holland


1 Answers

"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:

.SetOrdinal(dt.Columns.Count);

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:

var count = dt.Columns.Count;
dt.Columns.Add("Blah").SetOrdinal(count);

or even better:

dt.Columns.Add("Blah");
dt.Columns.SetOrdinal(dt.Columns.Count-1);

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.

like image 142
Jamie Treworgy Avatar answered Aug 15 '26 08:08

Jamie Treworgy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!