11

I have 2 overloaded C# functions like this:

private void _Insert(Hashtable hash, string tablename, Func<string, object[], SqlCommand> command)
private void _Insert(Hashtable hash, string tablename, Func<string, object[], OleCommand> command)

Basically one using OleCommand and the other SqlCommand for the return value of the function.

But the ugly thing about this is that I have to cast the function pointer to the correct type even though i feel the compiler should be able to resolve it without problems:

class RemoteDatabase
{    
      public SqlCommand GetCommand(string query, object[] values);
}

_Insert(enquiry, "Enquiry", (Func<string, object[], SqlCommand>)(_RemoteDatabase.GetCommand));

Is there any way tell the compiler to be smarter so that I don't have to do the type casting? Or did I do anything wrong?

EDIT: Added a bounty because I am really interested to learn. Thanks for any advice.

Alex R.
  • 4,664
  • 4
  • 30
  • 40
Jake
  • 11,273
  • 21
  • 90
  • 147

4 Answers4

8

While not answering your question directly, I did come across the following while writing up a test case, you can get it to compile by wrapping the call in another lambda. Which removes the explicit cast at the cost of another method call (at least I think so, haven't looked at the IL yet)

class RemoteDatabase
{
    public int GetCommand(){return 5;}
}

class Program
{

    static void Main(string[] args)
    {
        var rd = new RemoteDatabase();

        // Overloaded(1, rd.GetCommand); // this is a compile error, ambigous

        Overloaded(1, () => rd.GetCommand()); // this compiles and works

        Console.ReadLine();
    }

    static void Overloaded(int paramOne, Func<int> paramFun)
    {
        Console.WriteLine("First {0} {1}", paramOne, paramFun());
    }

    static void Overloaded(int paramOne, Func<string> paramFun)
    {
        Console.WriteLine("Second {0} {1}", paramOne, paramFun());
    }
}

EDIT- I found this post by Eric Lippert that answers this question

An interesting fact: the conversion rules for lambdas do take into account return types. If you say Foo(()=>X()) then we do the right thing. The fact that lambdas and method groups have different convertibility rules is rather unfortunate.

Community
  • 1
  • 1
BrandonAGr
  • 5,827
  • 5
  • 47
  • 72
7

EDIT: This is caused by process defined in section Overload resolution of C# specification. Once it gets the set of applicable candidate function members it cannot choose 'best function' because it isnt taking return type in the account during overload resolution. Since it cannot choose best function ambigous method call error occures according to spec.

However if your goal is to simplify method calls and avoid long casting to func you can use generics for and complicate _Insert method by a little bit like this for example:

public  void Main()
    {
        _Insert(new Hashtable(), "SqlTable", F1);
        _Insert(new Hashtable(), "OleTable", F2);
    }

    private static SqlCommand F1(string name, object[] array)
    {
        return new SqlCommand();
    }

    private static OleDbCommand F2(string name, object[] array)
    {
        return new OleDbCommand();
    }

    private void _Insert<T>(Hashtable hash, string tablename, Func<string, object[], T> command) 
    {
        if (typeof(T) == typeof(SqlCommand)) {
            SqlCommand result = command(null, null) as SqlCommand;
        }
        else if (typeof(T) == typeof(OleDbCommand)) {
            OleDbCommand result = command(null, null) as OleDbCommand;
        }
        else throw new ArgumentOutOfRangeException("command");
    }

Notice simplified method calls

_Insert(new Hashtable(), "OleTable", F1);
_Insert(new Hashtable(), "OleTable", F2);

that compile just fine

Valentin Kuzub
  • 11,703
  • 7
  • 56
  • 93
  • @Valentin this probably just answered my comment to Joel =) – Jake Jul 15 '11 at 04:32
  • pretty typical use of generics feature for some cases in C#. Obviously, not default use case. Used this way it can be seen as factory method based on generics mechanics. It is the only approach you can take in C# 2.0 for example which didnt include lambdas. You can add where T: DbCommand if both classes are DbCommand to get more typesafety at compile time. – Valentin Kuzub Jul 19 '11 at 19:54
  • I like it, but you could have entirely rid yourself of the type-specific code in the method body. Otherwise, you don't need generics and can just pass a string or a Type object. – hoodaticus Jul 20 '11 at 03:14
4

Can you use Func<string, object[], DbCommand>? That would also let you get rid of the overload and only need one function.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • I revisited my old project and see that this is may not be possible based on my (limited?) knowledge. Essentially, each _Insert is different in the data processing BEFORE passing in to Func(). In this case I cannot (don't know how to) test the return type before I even execute Func(). – Jake Jul 15 '11 at 03:56
1

well, since the return value indeed isn't taken into account, how about one of these: (note: i wrote a test project with slightly different code so there could be some sort of issues with it, but this should give the idea...)

public class RemoteDatabase
{    
      // changed to private, referenced by CommandWay1
      private SqlCommand GetCommand(string query, object[] values)
      {
          /* GetCommand() code */ 
      }

      public Func<string, object[], SqlCommand> CommandWay1
      {
          get
          {
             return (q,v) => GetCommand(q,v);
          }
      }

      // or, you could remove the above and just have this, 
      // with the code directly in the property
      public Func<string, object[], SqlCommand> CommandWay2
      {
          get
          {
             return
                (q,v) =>
                {
                   /* GetCommand() code */ 
                };
      }
}

then i was able to get each of these to compile with no casting:

_Insert(enquiry, "Enquiry", (q,v) => _RemoteDatabase.GetCommand(q,v));
_Insert(enquiry, "Enquiry", _RemoteDatabase.CommandWay1);
_Insert(enquiry, "Enquiry", _RemoteDatabase.CommandWay2);
shelleybutterfly
  • 3,216
  • 15
  • 32
  • Yup it works like a charm. Already got the idea from Brandon's Overloaded(). Thanks for the details. – Jake Jul 15 '11 at 04:34