From the course: Advanced C#: Functional Programming Patterns

Unlock this course with a free trial

Join today to access over 24,500 courses taught by industry experts.

Pipelining with generic methods

Pipelining with generic methods

Let's see if we can improve this code by using higher-order functions and generics. Now if you noticed in the prior example, these methods, they all have a similar signature. They take an int as a parameter and they output an int, and they're doing some operations inside the method. So I think I can make a generic version of this like so. It's called PerformOperation. So it's a PerformOperation of T. It's going to be an extension method of the T value. In my first example, it would be an int. And then the second parameter is a func of T. I call that the performer. That's the code that's going to perform the action. I'm also restricting this, so T can only be a struct for this demo. And then I return a T. So that's the basic signature of the prior examples. So now that I've done that, I can go up here and create a lambda variable or I should say a func variable, and use a lambda to set the code and do the same thing on line 18. And now I can say value = 5. And then I can call value…

Contents