-2

There are several approaches in another languages like

But what about implementation in c#? Any ideas?

Luuk
  • 12,245
  • 5
  • 22
  • 33
  • [Is it possible to convert F# code to C# code?](https://stackoverflow.com/questions/4818332/is-it-possible-to-convert-f-code-to-c-sharp-code). If you use that you can convert the solution given in the second link you gave in your question to C#. – Luuk Jun 12 '21 at 10:54
  • 1
    What are you looking for beyond `Action`/`Func`? – Jeroen Mostert Jun 12 '21 at 11:12
  • It does not matter: any idea is higly appreciated. – Anton Gridushko Jun 12 '21 at 11:17
  • ...well the idea is: use `Action`/`Func`. It's unclear why a strategy (which is essentially nothing more than a higher-order function, or at best a set of such functions) would need anything more complicated, especially since you're specifically asking for a functional style. (The usual O-O style would be to abstract it as an interface and pass that around.) Do you have an actual, practical programming problem to solve or are you looking for theory? Stack Overflow typically focuses on the former. – Jeroen Mostert Jun 12 '21 at 11:25
  • I try to find out something new, becaus I know, how OOP Strategy pattern works. – Anton Gridushko Jun 12 '21 at 12:01

1 Answers1

2

In my opinion, the Strategy Pattern is an 'anti-pattern'.

Fundamentally, this pattern suggests to utilize interfaces in order to abstract functions, which in turn it rephrases as 'strategies'.

A function abstraction is simply a delegate or function-pointer.

We do not need to create any classes, interfaces or any other OO-mumbo-jumbo, just to call it a 'pattern' and invent silly names in order to do 'Modern OOP'.

It is utterly absurd.

Now, sometimes people will tell, that the strategy-pattern is meant to design abstractions that consist of multiple functions (or members)...

...that is simply an interface.

So in order to use a 'functional approach' instead of the 'strategy pattern'... or rather a 'common-sense approach', instead of inventing silly nonsense... we use a delegate in C#:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> f)
{
    foreach (T item in source)
    {
        f(item);
    }
}

https://learn.microsoft.com/en-us/dotnet/api/system.action?view=net-5.0

https://learn.microsoft.com/en-us/dotnet/api/system.func-1?view=net-5.0

Purity
  • 331
  • 1
  • 8