tags:

views:

54

answers:

2

I have two functions:

double fullFingerPrinting(string location1, string location2, int nGrams)
double AllSubstrings(string location1, string location2, int nGrams)

I want to go in a loop and activate each function in its turn, and after each function I also want to print the name of the function, how can I do that?

+5  A: 
  1. Define a delegate type that is common to your functions.
  2. Create a collection of delegates for your functions
  3. Loop through the collection, invoking each delegate and using the Delegate.Method property to get the method name.

Example (edited to show non-static function delegates):

class Program
{
    delegate double CommonDelegate(string location1, string location2, int nGrams);

    static void Main(string[] args)
    {
        SomeClass foo = new SomeClass();

        var functions = new CommonDelegate[]
        {
            AllSubstrings,
            FullFingerPrinting,
            foo.OtherMethod
        };

        foreach (var function in functions)
        {
            Console.WriteLine("{0} returned {1}",
                function.Method.Name,
                function("foo", "bar", 42)
            );
        }
    }

    static double AllSubstrings(string location1, string location2, int nGrams)
    {
        // ...
        return 1.0;
    }

    static double FullFingerPrinting(string location1, string location2, int nGrams)
    {
        // ...
        return 2.0;
    }
}

class SomeClass
{
    public double OtherMethod(string location1, string location2, int nGrams)
    {
        // ...
        return 3.0;
    }
}
Chris Schmich
tanks!! you helped a lot!
does the functions has to be statics?? thats ruins me everything because this functions uses none statics functions...
@aharont: No, the function can be a member function on an object. I updated my answer to include an example of this.
Chris Schmich
ohh. ok, i got my mistake, tanks!
A: 

Not sure if this helps, but I did a post delegates and events that fire that you can use a delegate and attached it to a event which inturn if you call that event it will fire all of the delegates attached to that event, so no looping would be required.