I have a list with methods that I am calling from a loop like below (with the help of a previous question: Create a list with methods with a return value C#):
string method;
var methods = new List<(Func<string> analysismethod, string caption)>
{
(definitearticle, "Definite article"),
(indefinitearticle, "Indefinite article"),
};
for (int i = 0; i < methods.Count(); i++)
{
string gender = methods[i].analysismethod.Invoke();
if (gender != "Cannot determine")
{
method = methods[i].caption;
break;
}
}
What I want to do now is to add an optional argument (a string
) to each of the methods in methods
(so I can reuse them for other purposes as well) like in:
definitearticle (word = default)
{
}
However, when I try add the optional argument, I get these errors:
Error CS1950 The best overloaded Add method 'List<(Func<string> analysismethod, string caption)>.Add((Func<string> analysismethod, string caption))' for the collection initializer has some invalid arguments
Error CS1503 Argument 1: cannot convert from '(method group, string)' to '(Func<string> analysismethod, string caption)'
How can I solve this?
edit: The reason why I want to use them with a specified string sometimes is that I sometimes want to analyse them for a specific input, whereas I sometimes just want to check for a default position in a sentence that I store in a struct
:
public string indefinitearticle(string word = default)
{
if (word == default)
{
word = AnalysisData.wordBeforeNoun;
}
string gender = default;
if (word == "eine")
{
gender = "Fem";
}
else if (word == "ein")
{
gender = "Non fem";
}
return string.IsNullOrEmpty(gender) ? "Cannot determine" : gender;
}
Introduce overload methods
public string DefiniteArticle(string param1, string param2)
{
// calculate and return "some string";
}
public string DefiniteArticle()
{
return DefiniteArticle("default value1", "default value2");
}
Now with parameterless overload you are able to add it to the collection of Func<string>
to satisfy it's type and use "original" method for other purposes.
var delagates = new Func<string>[] { DefiniteArticle }
Notice that delegate are types as any other int
or string
- for being able to add method to the collection of delegates method should be same type. Overload method allows us to "decorate" original method with the required delegate type