Introduction
Passing collections between functions is a basic programming requirement. Usually I use any built-in .NET data structures such as a dictionary or list of any custom defined struct or class in order to do this. In many situations this procedure is something like create a list object and add values into it with or without a loop. Then pass that object into the function and finally extract values from that function using a loop. Here the collection act something like a bucket to keep the values together. In my experience, if the collection object creates only for this purpose, all these steps are unnecessary and causes lot of bugs (Sometimes the collection may tampered by some other code). So it was always my concern to avoid these issues. I found an alternative solution using functional programming.
The scenario
Suppose if I want to pass a set of key and value pair values into a function, usually I will declare the function like this.
public void PassValues(IDictionary<int,string> dict)
{
foreach (KeyValuePair<int,string> item in dict)
{
Console.WriteLine(string.Format("Key : {0}, Value : {1}", item.Key, item.Value));
}
}
The following code is use to call this function.
IDictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "One");
dict.Add(2, "Two");
dict.Add(3, "Three");
PassValues(dict);
The functional way
Using the functional programming we can avoid this dictionary and do the same thing in more flexible way. Most importantly, it will create an immutable collection. First step is to create two generic delegates.
public delegate void AddParam<TKey, TValue>(TKey key, TValue value);
public delegate void AddCollection<TKey, TValue>(AddParam<TKey, TValue> paramCollection);
The first delegate accepts two generic values and the second delegate accepts the first delegate as a parameter. Now we can rewrite the
PassValues
function as below.
public void PassValues(AddCollection<int,string> paramCollection)
{
paramCollection((key, value) => { Console.WriteLine(string.Format("Key : {0}, Value : {1}", key, value)); });
}
Since the PassValues
function can receive a function as parameter, it becomes a high order function. The final step is to call this function.
PassValues((addParam) =>
{
addParam(1, "One");
addParam(2, "Two");
addParam(3, "Three");
});
You can reuse this collection by passing a different piece of code. For example:
IList<string> lst = new List<string>();
paramCollection((key, value) => { if (key > 2) { lst.Add(value); } });
If you want to pass a different data structure, you need to declare new delegates.
Points of Interest
You should be careful while choosing this method. This is not suitable for the all the situations. For example if you want to persist this collection in an ASP.NET session or on the disk, better not to use this method.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.