views:

68

answers:

1

I'm curious if it's possible to create a delegate method with implicitly typed arguments. Here's what I'm trying to accomplish. This sort of thing won't compile for me, but it should give you an idea of what I'm trying to accomplish.

here's the functions I want to call using delegates:

class MyClass
{
    ArrayList function1(int param1, int param2)
    {
        ...do something...
    }
    ArrayList function2(string param3)
    {
        ...do something...
    }
}

And here's the class that calls them:

class MyOtherClass
{
    delegate ArrayList delFunc(params object[] args);

    myOtherClass()
    {
        MyClass myClassInstance = new myClass();
        delFunc myDelFunc1 = myClassInstance.function1;
        delFunc myDelFunc2 = myClassInstance.function2;

        myDelFunc1(1,2);
        myDelFunc2("hello world");
    }


}

Obviously in this example you would just actually call the provided functions. What I'm actually trying to do, is create a wrapper function which allows you to provide a function as a delegate with any possible argument list.

The only solution I can come up with is to make the functions in MyClass take param lists as well. However, that would make it very confusing to anyone directly calling these functions. Here's what I mean:

class MyClass
{
    ArrayList function1(params object[] args)
    {
        ...do something...
    }
    ArrayList function2(params object[] args)
    {
        ...do something...
    }
}

Now it compiles, but I need to guess, or read comments, to find out what to pass into function1 and function2. Also, where it once failed at compile time, it now fails at runtime. All very bad things...

I'm thinking there may be some syntax I'm missing for doing something like this

delegate ArrayList delFunc(MatchAnyArgumentSignature);

Cheers, Rob

+1  A: 

Just use Action<T> or Action<T1, T2, .....> :

public void Something(int arg1, int arg2, int arg3) {
  ...
}

and anywhere inside a method:

Action<int, int, int>  call = Something; 
call(1, 2, 3);

You cannot use var in this case.

Anyways, you shouldn't use ArrayList anymore.

Edit:

If those delegates should return something, there is Func<TResult>, Func<T1..TN, TResult>

Maxem
Great, that should do the trick! BTW, are ArrayLists deprecated or something?
Lockyer
Use List<T> instead of ArrayList
Maxem
k, thanks for your help!
Lockyer
Your welcome. One other thing: Its convention that methodnames are in CamelCase, just like classes.
Maxem