Search code examples
c#asp.netdelegatesgeneric-programming

Delegate for generic method return <T>


I have a method -

public T GetField<T> (string tableName, string fieldName)
{
    //Code
}

I need a delegate to hold this method. Not sure how to declare delegate for above method.

Now if I change my method

public T GetField<T> (string tableName, string fieldName, params IDbDataParameter[] parameters)
{
    //Code
}

public T Func<string,string ,string,IDbDataParameter[],T> GetFieldAction = GetField;// This is wrong

Any suggestion? Is it possible? Can I have a delegate which can hold generic return type method?

Is there any Func() workaround?


Solution

  • Why not Func<string, string, T>?

    Or, alternatively, if you don't want to use Func:

    delegate T MyDelegate<T>(string tableName, string fieldName);

    EDIT: Example code which addresses your comment:

    delegate T MyDelegate<T>(string tableName, string fieldName, params IDbDataParameter[] parameters);
    
    private T GetField<T>(string tableName, string fieldName, params IDbDataParameter[] parameters)
    {
      return default(T);
    }
    
    void Main()
    {
      MyDelegate<int> del = this.GetField<int>;
    }