I thought this may have been easy enough but doesnt seem so (might be that i need to learn this)
Here is some code i have working as an Extension for one of my types
public static IMySpecialClass[]? MyMultipleFunction(this string[]? values, float line)
{
if (values == null) return null;
List<IMySpecialClass> listClass = [];
foreach (var v in values)
{
listClass.Add(v.XXXX(line));
}
return [.. listClass];
}
I have this method but all i want to do is change/pass in the method that is called in the foreach loop
listClass.Add(v.XXXX(line));
the XXXX is the method i want to change depending on which function i want to execute.
XXXX is of string IMySpecialClass
type a void so i cant figure out a way to pass in or state which function i want to use depending on my requirements?
I know i can copy and paste the code and change the XXXX method and name the function different but is there a way to achieve this without copy/paste?
I read up on dynamic types but i feel i need some example to fill in some missing knowledge so be great if someone can show how this can be achieved (if possible) and maybe some reference for me to refer to at a later stage?
Edit
The current code after adding Action to the signature
public static IMySpecialClass[]? MyMultipleFunction(this string[]? values, float line, Func<string, float, IMySpecialClass> func)
{
if (values == null) return null;
List<IMySpecialClass> listClass = [];
foreach (var v in values)
{
listClass.Add(func(v.XXXX(line)));
}
return [.. listClass];
}
At present returns the error
There is no argument given that corresponds to the required parameter ‘arg2’ of ‘Action<string, float>’
If i remove the float paramter
Argument 1: cannot convert from ‘IMySpecialClass’ to ‘string’
3
You do not need this complex extension method. You can just use LINQ:
string[] values = new string[] { "a", "b", "c" };
IMySpecialClass[] result = values.Select(v => SomeMethod(v, line)).ToArray();
This will apply the method SomeMethod
to each element of the values
array. The results will be stored in a new array.
If I understood correctly, you can pass an Func<string, float, IMySpecialClass>, as in:
public static IMySpecialClass[]? MyMultipleFunction(this string[]? values, float line, Func<string, float, IMySpecialClass> func)
{
...
foreach (var v in values)
{
listClass.Add(func(v, line));
}
...
}
And call it like this:
var strings = new string[] { "a", "b", "c" };
Func<string, float, IMySpecialClass> func = CreateMySpecialClass;
strings.MyMultipleFunction(1f, func));
static IMySpecialClass CreateMySpecialClass(string str, float line)
{
...
}
Of course, there must be some CreateMySpecialClass method.
9