Question

for casting data of SqlDataReader I do these (example for common data types):

string name = reader["name"].ToString();  //for string


int i = 0; i = int.TryParse(reader["i"].ToString(), out i);       //for int
int i = reader.GetInt32(reader.GetOrdinal("i"));                  //or this again for int

bool b = reader.GetBoolean(reader.GetOrdinal("b"));               // for boolean

I want to create a class with these functions:

public static class gd{
   public static bool Bool(SqlDataReader rd, string name)
    {
         return rd.GetBoolean(rd.GetOrdinal(name));
    }
   public static int Int(SqlDataReader rd, string name)
    {
         int i=0;
         i = int.TryParse(reader["i"].ToString(), out i); 
         return i;
    }
}

and then just use:

int i=c.Int(reader,"i");
bool b=c.Bool(reader,"b");
DateTime dt = c.Date(reader,"dt");

I want to know is it a good idea to pass datareader as parameter? anyone has got a better Idea for casting datareader data?

Was it helpful?

Solution

Yes, it's OK to pass DataReader as parameter (as any other reference type). When you are passing reader, only reference to it is passed to another method. And it's OK to use methods to make your code more readable and maintainable.

You can write extension method in order to simplify your code:

public static class Extensions
{
    public static bool GetBoolean(this IDataReader reader, string name)
    {
         return reader.GetBoolean(reader.GetOrdinal(name));
    }

    public static int GetInt32(this IDataReader reader, string name)
    {
         return reader.GetInt32(reader.GetOrdinal(name));
    }
}

Usage will look like:

int i = reader.GetInt32("i");
bool b = reader.GetBoolean("b");

OTHER TIPS

Your idea seems fine (passing reference to SqlDataReader doesn't lag application) if you wish to handle exceptions internally. You could use methods provided by SqlDataReader class specifically for getting data in desired formats:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

Check if those methods are sufficent for you. If not, your static helper class seems okay, but I'd advise you to avoid duplicating functionality that's already implemented inside SqlDataReader, because what's the point of reinventing the wheel?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top