enum as index for DataRow

M

marc.gibian

I have been trying to improve the quality of my C# and ADO.NET coding.
One of the books I've read strongly advises against using string values
to address individual values in DataRow objects. This rings true to me
after years of avoiding string lookups whenever possible. But, when I
attempted to implement this recommendation I appear to run into casting
issues. Thus:

enum myFields {
field1 = 0,
field2 = 1
}

.....

ob = myDataRow[myFields.field1];

fails to compile, complaining the index argument cannot be converted
from myfields to int. Casting the index to int works just fine, though
I REALLY do not want to have to cast every use of this enum.

I have been doing some searching of the web and various newsgroups on
this topic. I find a general lack of discussion of this particular
issue, even though there is consensus that there is a performance gain
to be had by avoiding string lookups when possible in an easily
maintainable manner. The enum DataRow indexer technique does appear to
work well for VB.

I am beginning to wonder if the C# enum is so isolated that it is of
very limited utility. This would not be the first language to include a
constricted enum element.
 
N

Nicholas Paldino [.NET/C# MVP]

An easy way to get around this would be to define a sealed class which
exposes the field indexes as constants or static read only values (it's up
to you how you do this). This would allow you to reduce the code as you
desire, and get the speed benefits of not having to map the field name to
the column.

The reason it doesn't work is that to .NET the enumeration is a separate
type, not the actual type that the enumeration is bounded by (int, long,
etc, etc). This is why it requires the cast.

As for whether or not which is better, that's for you to decide.
Personally, I like the purity of the approach they took, especially with the
simple workaround.

Hope this helps.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You either define constants:
public constant int Table1.Field1 = 0;

or you use the cast

Personally I use the first approach especially in applications running on a
PocketPC , the improvement were noticeable.


Cheers,
 
R

Robby

Could you not use a Structure with all Shared (I think Stactic in C#)
variables instead of an Enum? I think the only trick to this is that you
need at least one non-Shared (non-Static) variable in the Structure
declaration. You could make this variable a Byte so it takes up as little
memory as possible. This would work with out casting as the Structure
variables would return the correct type.

Hope this helps

Robby
VB.Net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top