views:

239

answers:

1

I'm trying to define a delegate function that will return an IEnumerable. I'm having a couple issues - I think I'm close, but need some help getting there...

I can define my delegate fine:

 public delegate IEnumerable<T> GetGridDataSource<T>();

Now how do use it?

 // I'm sure this causes an error of some sort
 public void someMethod(GetGridDataSource method) { 
      method();
 }

And here?

 myObject.someMethod(new MyClass.GetGridDataSource(methodBeingCalled));

Thanks for tips.

+4  A: 

Hi, you need to specify a generic type parameter in your "someMethod" declaration.

Here's how it should look:

public void someMethod<T>(GetGridDataSource<T> method) 
{ 
      method();
}

When you call the method you won't need to specify the type parameter because it will be inferred from the method that you pass in, so the call will look like this:

myObject.someMethod(myObject.methodBeingCalled);

Here's a full example you can paste into VS and try out:

namespace DoctaJonez.StackOverflow
{
    class Example
    {
        //the delegate declaration
        public delegate IEnumerable<T> GetGridDataSource<T>();

        //the generic method used to call the method
        public void someMethod<T>(GetGridDataSource<T> method)
        {
            method();
        }

        //a method to pass to "someMethod<T>"
        private IEnumerable<string> methodBeingCalled()
        {
            return Enumerable.Empty<string>();
        }

        //our main program look
        static void Main(string[] args)
        {
            //create a new instance of our example
            var myObject = new Example();
            //invoke the method passing the method
            myObject.someMethod<string>(myObject.methodBeingCalled);
        }
    }
}
DoctaJonez