views:

30

answers:

3

What should be more appropriate to use when you want to initialize class properties from datatable.

i.e.

name=dt.Rows[0][0] or name=dt.Rows[0]["Name"]

Which approach is more scalable any easy to handle. Currently I uses 2nd approach but feels like if I use indexes rather than name that i only need to change stored procedures rather that UI also.

But compromises readability of code. So What should I go for

+1  A: 

One option is to have something in between:

private const int NameColumn = 0;
...
name = dt.Rows[0][NameColumn];

That gives you one place to change if the column ordering/definitions change, but also gives readable code at the point of access. I'm not sure it addresses the issue of having to change both the UI code and the stored procedures at the same time: if your SPs are effectively changing their public interface, you should expect to change the UI code. However, this approach can reduce the pain of that change, as well as not littering your code with magic values.

(You might also want to consider strongly typed datasets... or moving to a non-DataTable data solution such as the Entity Framework. It may not be appropriate in your situation, but it's worth considering.)

Jon Skeet
@Jon: This means somewhat moving towards TypedDataSets. Is it so Jon ?
Shantanu Gupta
@Shantanu: Not necessarily. It's not changing which types you're dealing with, after all - just how you access particular columns. Now admittedly moving to strongly typed datasets may well be an appropriate step, but you definitely don't *have* to.
Jon Skeet
considering that might be, let's say, 10 tables per dataset each with 10 columns, wouldn't declaring fields for each column be considered an overhead?
devnull
@devnull: Less overhead than having the same 100 magic values scattered throughout the code. Suppose two tables both use the same column name ("CustomerName") and then *one* of them changes... if you've got the two as separate fields to start with, it's trivial to get that right. If you've used the string literal "CustomerName" for both columns throughout your code, you've got to examine every bit of code using it. Ouch.
Jon Skeet
+1  A: 

Column names, as it makes it all more readable. If you're going to change stored procedures, using column indexes won't help much cause you might be changing the number or the order of columns.

devnull
A: 

Using a numeric index is faster than repeatedly using the string index. You can compute the numeric index at runtime once before you loop through table rows like so:

int indexName = dt.Columns.IndexOf("Name")
kbrimington