KGB91
KGB91

Reputation: 679

Create a list with methods with a return value C#

I a making a little program that wants to analyse the gender of German nouns in a corpus. For that I have created some methods with a string as return value. For instance, I want to check if there is a definite in front of the noun in the corpus and see if it contains "der", "die" or "das". Deepening on which it returns different values. Like below:

private string definitearticle()
{ 
    // code, where gender is the string which we return - if we can't determine
    // the gender it returns "Cannot determine"
    return gender;
}

private string indefinitearticle()
{ 
    // code, where gender is the string which we return - if we can't determine
    // the gender it returns "Cannot determine"
    return gender;
}

I want to loop each one of the methods one by one until I no longer get "Cannot determine" as the return value like below with a list of pointers to the methods (like in Storing a list of methods in C#):

var methods = new List<(System.Action check, string caption)>()
{
    (definitearticle, "Definite article"),
    (indefinitearticle, "Indefinite article"),
};

foreach (var method in methods)
{
    gender = method.check.Invoke();
    if (gender != "Cannot determine")
    {
        // store the outcome that was returned to a list
        break;
    }
}

The problem is that I do not know how to use a List with methods that have a return value (in this case a string). Could anyone help me out here?

Upvotes: 0

Views: 1724

Answers (1)

Despacito 2
Despacito 2

Reputation: 494

If you need to store a method as a type that has a return value, you should use Func<TResult> instead of Action. It works the same way as an action, except that you additionaly can input the return type as the last generic type. So if you for example had a method where it had two parameters with the types of int and bool and a return type of string, you would say

var myReturnMethod = new Func<int, bool, string>((intVal, boolVal) => intVal.ToString() + boolVal.ToString());

In your case, just replace your methods variable initialization with this code:

var methods = new List<(Func<string> check, string caption)>
    {
        (definitearticle, "Definite article"),
        (indefinitearticle, "Indefinite article"),
    };

Edit:

On request of the OP, here's how you'd initialize the methods variable if you only wanted it to contain a collection of the methods, without the caption:

        var methods = new List<Func<string>>
        {
            definitearticle,
            indefinitearticle,
        };

More info on Functions can be found at the official microsoft docs.

Upvotes: 3

Related Questions