FreeVice
FreeVice

Reputation: 2697

How to Add entity to Dictionary Object Initializer?

I need to pass html attributes.

It is possible to pack into one expression code some like this?

var tempDictionary = new Dictionary<string, object> { 
   { "class", "ui-btn-test" }, 
   { "data-icon", "gear" } 
}.Add("class", "selected");

or

new Dictionary<string, object> ().Add("class", "selected").Add("diabled", "diabled");

?

Upvotes: 0

Views: 288

Answers (1)

Chris Gessler
Chris Gessler

Reputation: 23113

What you are referring to is known as method chaining. A good example of this is the StringBuilder's Append method.

StringBuilder b = new StringBuilder();
b.Append("test").Append("test");

This is possible because the Append method returns a StringBuilder object

public unsafe StringBuilder Append(string value)

But, in your case, the Add method of Dictionary<TKey, TValue> is marked void

public void Add(TKey key, TValue value)

Therefore, method chaining is not supported. However, if you really wanted to use method chaining when adding new items, you could always roll your own:

public static Dictionary<TKey, TValue> AddChain<TKey, TValue>(this Dictionary<TKey, TValue> d, TKey key, TValue value)
{
  d.Add(key, value);
  return d;
}

Then you could write the following code:

Dictionary<string, string> dict = new Dictionary<string, string>()
  .AddChain("test1", "test1")
  .AddChain("test2", "test2");

Upvotes: 1

Related Questions