[C#] function as parameter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

[C#] function as parameter

How to pass function as parameter for another function? I want to use inline function. Create and use it at the same time Delegate creation: `public delegate bool delCheck(string value);`

15th Jan 2017, 8:03 AM
WittyBit
WittyBit - avatar
5 Answers
+ 4
So, simply you can create a function, and then pass it as parameter `public bool MyCheck(string str) { // Some checking return true; } AddCheck(MyCheck); // Passing function as paramter }` Second variant is to create inline function: `AddCheck(new delCheck((str) => { return true; });` There i created anonymouse function and passed it as parameter. 3rd way to do it is use Func<bool> You can specify parameters, separating them by coma, and last type is return type. Example: Func<int, bool> will have parameter of type int and return bool. `AddCheck(Func<string, bool> checker) { // checks }` It might be useful to create many checks
14th Jan 2017, 4:34 PM
WittyBit
WittyBit - avatar
+ 5
@Ken Kaneki It is like sorting. You need to sort some list of object only ones, but yes, in most cases i prefere to write functions(Only if i dont have 10 or more checks :/) P.S joking maybe
15th Jan 2017, 8:18 AM
WittyBit
WittyBit - avatar
+ 4
@Ken Kaneki Ok, nice. But if i want to create inline method, ah? ;~) Anyway thx for code, i'm too lazy to write it :/
15th Jan 2017, 8:05 AM
WittyBit
WittyBit - avatar
+ 3
I just wrote a working example of how you can define and use a function as a parameter for another function. I'll copy it here below, and you can find it on my codes, and play with it there. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { Function(Checker); } static bool Checker() { return true; } static void Function(Func<bool> check) { if (check()) { Console.WriteLine("2017 meme"); } } } }
15th Jan 2017, 7:56 AM
Dao
Dao - avatar
+ 2
If you want it to be inline, then yeah, lambdas are the way to go, but do you really want to make condition-checking functions that way? Reusability seems like a key feature for these types of function...
15th Jan 2017, 8:10 AM
Dao
Dao - avatar