I am trying to create a generic method that will take a Func parameter.
traditional func is that we create methodOne() and send it as a parameter to another method. However, that will defeat the purpose of making the method I am trying to create as a generic.
My code:
public static List<T> ExecuteQuery<T>(string connection,
string commandText,
Func<SqlDataReader, List<T>> myMethodName)
{
List<T> items = new List<T>();
SqlDataReader sqlDataReader = null;
try
{
using (SqlConnection con = new SqlConnection(connection))
{
using (SqlCommand cmd = new SqlCommand(commandText, con))
{
try
{
con.Open();
sqlDataReader = cmd.ExecuteReader();
items = myMethodName(sqlDataReader);
}
catch (Exception ex)
{
if (sqlDataReader != null) sqlDataReader.Close();
cmd.Dispose();
throw ex;
}
finally
{
if (sqlDataReader != null) sqlDataReader.Dispose();
cmd.Dispose();
}
}
}
}
catch (Exception)
{
throw;
}
return items;
}
Trying to call the method above like this:
public List<Function> GetDeletedFunctions(string connectionString)
{
SqlDataReader sqlDataReader = null;
List<Function> functions;
string cmdText = @"SELECT * FROM Table "; // dumy query
functions = DbHelper.ExecuteQuery<Function>(
connectionString,
cmdText,
List<Function>(sqlDataReader)
{
var f =
(from x in sqlDataReader.Cast<DbDataRecord>()
select new Function
{
Param1 = DbHelper.GetValue<string>("Param1 ", x),
Param2 = DbHelper.GetValue<string>("Param2", x),
}).ToList();
return f;
} );
}
Compile Time Error:
Error CS1955 Non-invocable member 'List' cannot be used like a method.
I am assuming there is a syntax issue here and its driving me nuts. Any suggestions?
sqlDataReader.