Click here to Skip to main content
15,914,905 members
Articles / Programming Languages / C#
Tip/Trick

Passing collections between functions - The functional way

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 Jun 2012CPOL2 min read 7.3K   5  
An alternate method to pass collection of values into a function using the techniques of functional programming.

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.

C#
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.

C#
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.

C#
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.
C#
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.

C#
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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) self employed
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --