Moshisho
Moshisho

Reputation: 2981

How to implement a custom delegate that is in a static class?

I want to write a generic method that allows me to use a pattern of test methods that returns a boolean with the result and outputs a string message:

public delegate bool TestMethodDelegate<string, bool>(out string message);

I use it in a static class (and it is declared in that class):

public static void ExecuteTestMethodDelegate(TestDelegate<string, bool> aTestMethod)
{
    // do repeated stuff before
    string message;
    bool result = aTestMethod(out message);
    // do repeated stuff after
}

Now I want to call this method from multiple places in the code but can't get it right... tried several options, like:

string message;
CommonTests.ExecuteTestMethodDelegate(() => return IsAppInstalled(out message));

Needless to say, this doesn't compile... any help will be appreciated.

Upvotes: 2

Views: 834

Answers (3)

Omar
Omar

Reputation: 16623

It ins't allowed to write:

public delegate bool TestMethodDelegate<string, bool>(out string message);

Because you're trying to declare a generic delegate by using string and bool as a type. So what about:

public delegate bool TestMethodDelegate<T>(out T message);

And:

public static void ExecuteTestMethodDelegate(TestDelegate<string> aTestMethod)
{
   string message;
   bool result = aTestMethod(out message);
}

So you can do:

CommonTests.ExecuteTestMethodDelegate(IsAppInstalled);

But as you can see you can't use message here. So a very simple solution could be:

public static void ExecuteTestMethodDelegate(TestMethodDelegate<string> aTestMethod, out string aParameter){
    bool result = aTestMethod(out aParameter);
}

And then:

string message;
CommonTests.ExecuteTestMethodDelegate(IsAppInstalled, out message);

Upvotes: 1

Charles Mager
Charles Mager

Reputation: 26213

A delegate can contain type parameters, but what you have is invalid - you can't specify as you have, it should be declared:

public delegate bool TestMethodDelegate(out string message);

To execute:

CommonTests.ExecuteTestMethodDelegate(IsAppInstalled);

If you want the message output and return result from this static method, you'd have to change the signature of the static method:

public static bool ExecuteTestMethodDelegate(TestMethodDelegate method, out string message)
{
    // do repeated stuff before
    bool result = method(out message);
    // do repeated stuff after

    return result;
}

Upvotes: 1

Lee
Lee

Reputation: 144136

You need to remove the generic parameters from your delegate:

public delegate bool TestMethodDelegate(out string message);

and

public static void ExecuteTestMethodDelegate(TestMethodDelegate aTestMethod) { .. }

Upvotes: 2

Related Questions