If you are familiar with ASP.NET MVC then you might have seen or used a method like this where the method take an object as a parameter and you can pass multiple key pair value through that object. Here is an example of ASP.NET MVC method ActionLink which takes five parameters (overloaded) as input and generate a HTML friendly link:

 
@Html.ActionLink(“Link text”, “ActionName”, “ControllerName”, 
    new { id = 1 }, 
    new { @class = “html-link”, title = “Some title”, data_id = 1 })

Output:

 
<a href="/ControllerName/ActionName?id=1"  
    class="html-link" title="Some title" data-id="1">Link text</a>

As you can see, here fourth and fifth parameter is an object and we are able to pass multiple key pair value to those objects. It’s very useful when you need one or more anonymous key pair value as input with a friendly way to call the method. Now, if you have a method taking an object as input, like above, you need to convert that object to IDictionary<string, object>.

Here is an extension method which will do the job for you:

 
public static class ObjectHelper 
{ 
    public static IDictionary<string, object> ToDictionary(this object obj) 
    { 
        BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance; 
        Dictionary<string, object> dictionary = new Dictionary<string, object>(); 
 
        foreach (PropertyInfo property in obj.GetType().GetProperties(publicAttributes)) 
        { 
            if (property.CanRead) 
            { 
                dictionary.Add(property.Name, property.GetValue(obj, null)); 
            } 
        } 
 
        return dictionary; 
    } 
}

Now let’s create a method which takes an object as parameter and see how this extension really works:

 
class Program 
{ 
    static void Main(string[] args) 
    { 
        DisplayKeyPairValues(new { FirstName = "Sahidul", LastName = "Islam", Nickname = "Shishir" }); 
 
        Console.ReadKey(); 
    } 
 
    static void DisplayKeyPairValues(object obj) 
    { 
        IDictionary<string, object> parameters = obj.ToDictionary(); 
 
        foreach (var keyPairVal in parameters) 
        { 
            Console.WriteLine(string.Format("{0}: {1}", keyPairVal.Key, keyPairVal.Value)); 
        } 
    } 
}

If you run this program you will have this output on your screen:

 
FirstName: Sahidul 
LastName: Islam 
Nickname: Shishir

As you can see on the above, I have created a simple method which takes object as a parameter and display all of its key value on the screen. It’s really simple and easy. Most of the time, in a situation like this, you will find this very useful.