Get Schooled at New Horizons

Info and insights from New Horizons Computer Learning Centers. 22 locations to serve you.
Start exploring

How to use delegates in C# to create callback functions (JavaScript)

One of the most useful features in JavaScript is that you can pass one function into another as an argument, so that it can be executed at the appropriate time. This callback design pattern allows you to write very flexible functions that allow the caller to decide what will happen in various scenarios.


As a simplistic, bare-bones example, consider the following JavaScript function that takes a string and a callback function as parameters, uses the first parameter to retrieve a value from another function, and then passes the result as a parameter into the callback function:


function applyToConfigVal(strConfigKey, callBack)
strVal = getConfig(strConfigKey);
return callBack(strVal);

You may wonder how to do a similar thing in C#. There are a few different ways, but one is with delegates. Because of C#’s strict typing paradigm, we don’t pass in any function, but rather a function declared to return a specific type. (There are ways to make the type more flexible, but delegates are designed to help ensure strict typing so that anyone who uses the code will only pass code with the expected type.) So in the following example, we declare a delegate to create a certain type (we’re calling it “del” here) that in term represents an action returning a certain type (e.g., a string array in this example), which we can use to pass a callback function. The rest of the example is similar to what we showed above in JavaScript:


delegate string[] del(string s);
string[] applyToConfigVal(string strConfigKey, del callBack)
string strVal = ConfigurationManager.AppSettings[strConfigKey];
return callBack(strVal);

Now, to call our sample function using a callback, we declare a variable having the type we created, which stores an action that we notate through what’s called a lambda expression. In this case, that action involves taking a string parameter and calling its Split method (although we could also use it to call any custom function …e.g., myFunction(s) instead of s.Split(‘|’)). Then we can pass that into our function as a callback:

del callBack = s => s.Split(‘|’);
string[] arrResult = applyToConfigVal(“MyConfig”, callBack);


Leave a Reply