Neo
Neo

Reputation: 2405

Class function to return different objects

In short I am writing a class handler to handle to database integration of some software I am writing for myself, however as there is not always a connection to the remote database I thought I would use SQLCE to create a local database buffer so when a connection is made the changes can be synchronized.

So far it is going well except for the parameters. The function I am looking to call is shown below however this function is complaining about invalid arguments.

public Object run(string query, List<Object> dbparams = null)
    {
        if (MyDB.isConnected())
        {
            return MyDB.run(query, dbparams);
        }
        else
        {
            SqlCeCommand sql = _OfflineConnection.CreateCommand();
            sql.CommandText = query;
            if (dbparams.Count > 0)
            {
                sql.Parameters.AddRange(dbparams.ToArray());
            }
            return sql;
        }
    }

MyDB.run is the exact same code as in the else statement except for mysql, the line that it is moaning about is the return mydb.run as the mydb class is expecting the dbparams list to be of mysqlparameters.

Does anyone know how I can achieve this? I attempted to use LINQ to do a convert but that failed miserably.

EDIT

At present I have the following working but I am sure there is a cleaner solution

public Object run(string query, List<Object> dbparams = null)
    {
        if (MyDB.isConnected())
        {
            List<MySqlParameter> mydbparams = null;
            for (int i = 0; i < dbparams.Count; i++)
            {
                mydbparams.Add((MySqlParameter)dbparams[i]);
            }
            return MyDB.run(query, mydbparams);
        }
        else
        {
            SqlCeCommand sql = _OfflineConnection.CreateCommand();
            sql.CommandText = query;
            if (dbparams.Count > 0)
            {
                sql.Parameters.AddRange(dbparams.ToArray());
            }
            return sql;
        }
    }

Upvotes: 2

Views: 139

Answers (1)

Eren Ers&#246;nmez
Eren Ers&#246;nmez

Reputation: 39085

A bit cleaner solution would be

mydbparams = dbparams.Cast<MySqlParameters>().ToList();

Also, you should check for and handle the null condition of dbparams.

Upvotes: 2

Related Questions