Jamie
Jamie

Reputation: 864

Issue with C#' generics, how to pass through input and output via a Func

private static K ExecuteStoredProcedure<K>(string connectionString, string storedProcedure, SqlParameter[] parameters, Func<I, K> readFunction)

Example usage is shown below:

 return ExecuteStoredProcedure<SqlDataReader, Dictionary<string, string>>(
     connectionString, 
     "uspSearchStatisticsSelectByTokenPerDayGroupByDate", 
     parameters, 
     (reader) =>
     {
         reader.Read();
         int readCount = reader.FieldCount;

         Dictionary<string, string> results = new Dictionary<string, string>();
         results.Add("FailedRequests", Convert.ToString(reader[5]));
         results.Add("TotalRequests", Convert.ToString(reader[4]));
         results.Add("AverageResponseTime", Convert.ToString(reader[3]));

         return results;
     }
 );

The compiler comes back with

Error 520 The type or namespace name 'I' could not be found (are you missing a using directive or an assembly reference?)

but I thought it should be able to reference that?

Update: I was trying to go for something too generic and didn't really need it.

I've gone with the following... private static K ExecuteStoredProcedure<K>(string connectionString, string storedProcedure, SqlParameter[] parameters, Func<SqlDataReader, K> readFunction)

Upvotes: 1

Views: 530

Answers (4)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Your static method at the top declares only one type parameter, called K. Did you mean to have two, like static K ExecuteStoredProcedure<I, K>( ... )? Because when you call the method, you do supply two type parameters.

The compiler error is quite clear: You say Func<I, K>, but nowhere is a type I defined.

Upvotes: 1

Camilo Aguilar
Camilo Aguilar

Reputation: 129

Your reader is only returning Dictionary and on how you are using your code K = Dictionary so you are missing the value for I, maybe you declare bad the functions or you need to fix the return value.

Upvotes: 0

Guffa
Guffa

Reputation: 700382

As the input parameter of the function is known, it shouldn't be generic. Just make the parameter Func<SqlDataReader, K> readFunction.

Upvotes: 2

millimoose
millimoose

Reputation: 39960

Your function is generic over I and K. The signature needs to be:

K ExecuteStoredProcedure<I, K>(...)

Upvotes: 9

Related Questions