Question

What nice about JQuery which is a great JavaScript library is to be able to get the element you are working on as return value. Here is an example of what I am referring :

$(function() { 
    $("#poo").css("clear", "both").css("margin", "10px");
});

What I would like to try to implement here is identically same as above code for C# IDictionary interface. My intention is to be able to right code as follows :

IDictionary<string, string> myDictionary = 
    new Dictionary<string, string>().
        Add("key1", "value1").
        Add("key2", "value2").
        Add("key3", "value3");

So I have created an extension method as below for IDictionary :

public static IDictionary<string, string> AddAndReturn(this IDictionary<string, string> dictionary, string key, string value) {

    dictionary.Add(key, value);
    return dictionary;
}

And now I am able to use it like :

IDictionary<string, string> poo = 
    new Dictionary<string,string>().
        AddAndReturn("key1", "value1").
        AddAndReturn("key2", "value2").
        AddAndReturn("key3", "value3");

So, as for the question here, what I wonder is whether I am following the right path here or not.

Is what I am doing a poor man's fluent interface implementation or totally unrelated to that?

Is there any known case for this implementation in C#?

Was it helpful?

Solution

While your implementation pattern is correct (and a common one at that,) your use case is probably not the best choice. Object Collection initializers work for dictionary types too:

var poo =  new Dictionary<string,string> {
        { "key1", "value1" },
        { "key2", "value2" },
        { "key3", "value3" }, // this is permissible
};

The compiler magically turns this into Add(string, string) calls. Btw, the apparently erroneous comma after the last pair is deliberate. The compiler allows this so you can simplify logic in code generators such as T4.

OTHER TIPS

I would also like to add something regarding " Is there any known case for this implementation in C#?"

The StringBuilder.Append method returns the StringBuilder, making the method chainable, such as sb.Append("a").Append("b"). Append("c").

But there aren't many other examples like that in .Net.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top