Casting SqlDataReaders

What are the benefits of replacing (int)reader[0] with reader.GetInt32(0) ? I’m sure that such casting functions exist for some reason, but besides the fact that it feels more aesthetically pleasing to avoid the cast, I’m not sure what these reasons are.

+4
source share
3 answers

In the code ....

  void OneWay() { System.Data.SqlClient.SqlDataReader reader = null; int i = reader.GetInt32(0); } void OtherWay() { System.Data.SqlClient.SqlDataReader reader = null; int i = (int)reader[0]; } 

In IL

 .method private hidebysig instance void OneWay() cil managed { .maxstack 2 .locals init ( [0] class [System.Data]System.Data.SqlClient.SqlDataReader reader, [1] int32 i) L_0000: nop L_0001: ldnull L_0002: stloc.0 L_0003: ldloc.0 L_0004: ldc.i4.0 L_0005: callvirt instance int32 [System.Data]System.Data.Common.DbDataReader::GetInt32(int32) L_000a: stloc.1 L_000b: ret } .method private hidebysig instance void OtherWay() cil managed { .maxstack 2 .locals init ( [0] class [System.Data]System.Data.SqlClient.SqlDataReader reader, [1] int32 i) L_0000: nop L_0001: ldnull L_0002: stloc.0 L_0003: ldloc.0 L_0004: ldc.i4.0 L_0005: callvirt instance object [System.Data]System.Data.Common.DbDataReader::get_Item(int32) L_000a: unbox.any int32 L_000f: stloc.1 L_0010: ret } 

So, IL is different, but I doubt that there is any noticeable difference between them. Perhaps after a million iterations you will see the difference, but hardly.

+5
source

The first one can also accept the column name as a string, not an index, and will try to pass the column value to int. The latter accepts only the index, and the casting will not be performed.

+1
source

reader [0] returns the system reader System.Object, (int) [0], actually performs translation from Object to Int32.

If you call GetXXX (0) methods, no conversions are performed. Therefore, the data received from the stream should already be the type of the specified method.

If the type of data received does not match or the column has DBNull, it throws an InvalidCastException.

+1
source

All Articles