Am I able to make this method generic?
public static List<int> GetUnshippedOrders(string server,string port,string database,string username,string password, string orderStatus)
{
var orderNumbers = new List<int>();
using (var conn = ConnectToMySql(server, port, database, username, password))
{
var command = new MySqlCommand("SELECT OrderNumber FROM orders WHERE OrderStatus = @orderStatus;", conn);
command.Parameters.AddWithValue("@orderStatus", orderStatus);
var reader = command.ExecuteReader();
while (reader.Read())
{
orderNumbers.Add(Convert.ToInt32(reader[0]));
}
}
return orderNumbers;
}
I want to be able to handle various return types as the order number referenced to will change depending upon the schema of the database being connected to, I would prefer not to have to overload this method for each possible return type (plus I want to learn generics).
The database schema is dictated by various web services, none of which are under my control.
Also of special note, orderStatus can be a variety of types as well ( mostly string and int)
If the logic to determine the return type is internal to the method, a generic return type isn’t going to help since you need to be able to specify the return type when calling a generic method. You could change the return type to
List<object>and then handle casting back to the concrete type after the method returns. It’s ugly, but it works.If the caller knows what type to expect when calling the method, you could simply change
List<int>toList<T>and support generics that way.