0

I have a function which performs an SQL query. Depending on a registry value, it will either hit SQL Server or SQL Server Compact Edition. If it is using SQL Server CE, the line setting the recordSet variable should read like this:

SqlCeDataReader recordSet = da.ExecuteSQLCommand(selectCommand);

For SQL Server, it should read like this:

SqlDataReader recordSet = da.ExecuteSQLCommand(selectCommand);

I am trying to put all this in an if/then statement at the beginning at the function but cannot seem to figure out how to set the Type within the if/then. Here is my (partial) code:

public static string SqlQuery(string selectCommand, int regval)
{
    var recordSet = null;
    string selectCommand = "select * from whatever";

    if (regval == 0)
    {
        SqlDataReader recordSet = null;
    }
    else
    {
        SqlCEDataReader recordSet = null;
    }

    recordSet = da.ExecuteSQLCommand(selectCommand);
}

The problem is that unless I declare the recordSet variable before the if/else, I cannot use it after. However, if I declare it before the if/else, I cannot change the type.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Progger
  • 2,266
  • 4
  • 27
  • 51
  • Do the classes have a common ancestor? – Lefteris E Apr 08 '13 at 13:53
  • 1
    I can't see how you'd expect this to work. What's the type of `da`? You're calling the same method in both cases, so you should be able to just use the declared return type. – Jon Skeet Apr 08 '13 at 13:54
  • declare it as DbDataReader before the if – Lefteris E Apr 08 '13 at 13:56
  • @LefterisE - I believe both are inherited from IDataReader. If I declare it as IDataReader first, what would I need to do to get to a more specific type, if that is even possible? – Progger Apr 09 '13 at 18:14

1 Answers1

8

You can't do that. Variables' types are really set in stone at compile time unless you use dynamic.

You could use the common interface IDataReader. Other standard ADO.NET clients such as for MySQL and SQLite implement this too.

Edit

Here is a sample

public static string SqlQuery(string selectCommand, int regval)
{
    IDataReader recordSet = null;
    string selectCommand = "select * from whatever";
    recordSet = da.ExecuteSQLCommand(selectCommand);
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Suggest the author make the answer more emphatic and explain polyMorphism. http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming – Charles Bretana Apr 08 '13 at 14:13
  • So would I be able to accomplish what I am trying to do by using a dynamic type? Is there an example you could show me? – Progger Apr 09 '13 at 18:41