{"id":579,"date":"2016-02-01T18:03:10","date_gmt":"2016-02-01T18:03:10","guid":{"rendered":"http:\/\/tpodolak.com\/blog\/?p=579"},"modified":"2016-02-01T18:22:59","modified_gmt":"2016-02-01T18:22:59","slug":"abusing-collection-initializers","status":"publish","type":"post","link":"https:\/\/tpodolak.com\/blog\/2016\/02\/01\/abusing-collection-initializers\/","title":{"rendered":"Abusing collection initializers"},"content":{"rendered":"<p>Most of .NET developers are familiar with collection initializers syntax. Long story short, this language feature allows you to replace this ugly syntax<\/p>\n<pre lang=\"csharp\">\r\nvar numbers = new List<int>();\r\nnumbers.Add(1);\r\nnumbers.Add(2);\r\nnumbers.Add(3);\r\nnumbers.Add(4);\r\n<\/pre>\n<p>with much shorter and cleaner one<\/p>\n<pre lang=\"csharp\">\r\nvar numbers = new List<int> { 1, 2, 3, 4 };\r\n<\/pre>\n<p>The more interesting thing is the fact that you can leverage this syntax not only for build-in collections but also for your custom classes. In order to do that your class must implement <i>IEnumerable<\/i> interface and expose public <i>Add<\/i> method. Let&#8217;s assume that we have some real case scenario and we have class which looks like that<\/p>\n<pre lang=\"csharp\">\r\npublic class StatusMessages : IEnumerable<StatusMessage>\r\n{\r\n    private List<StatusMessage> messages = new List<StatusMessage>();\r\n\r\n    public IEnumerator<StatusMessage> GetEnumerator()\r\n    {\r\n        return this.messages.GetEnumerator();\r\n    }\r\n\r\n    IEnumerator IEnumerable.GetEnumerator()\r\n    {\r\n        return this.messages.GetEnumerator();\r\n    }\r\n}\r\n\r\npublic class StatusMessage\r\n{\r\n    public string Text { get; set; } = string.Empty;\r\n    public string SourceSystem { get; set; } = string.Empty;\r\n    public int StatusCode { get; set; }\r\n\r\n    public StatusMessage()\r\n    {\r\n    }\r\n\r\n    public StatusMessage(string text)\r\n    {\r\n        this.Text = text;\r\n    }\r\n\r\n    public override string ToString()\r\n    {\r\n        return $\"Text: {this.Text} StatusCode: {this.StatusCode} SourceSystem: {this.SourceSystem}\";\r\n    }\r\n}\r\n<\/pre>\n<p>This is a simple wrapper over the List<StatusMessage>. At this moment we can&#8217;t use collection initializer when constructing objects of this classs. However by adding method <i>Add<\/i> <\/p>\n<pre lang=\"csharp\">\r\npublic class StatusMessages : IEnumerable<StatusMessage>\r\n{\r\n    \/\/ rest of the code omitted for brevity\r\n    public void Add(StatusMessage message)\r\n    {\r\n        this.messages.Add(message);\r\n    }\r\n    \/\/ rest of the code omitted for brevity\r\n}\r\n<\/pre>\n<p>we can create a new instance of that class just like we would do with <i>List<StatusMessage><\/i><\/p>\n<pre lang=\"csharp\">\r\nvar messagesAddInitializer = new StatusMessages\r\n            {\r\n                new StatusMessage(\"y\"),\r\n                new StatusMessage(\"x\"),\r\n            };\r\n<\/pre>\n<p>What is more, it is possible to have multiple overloads of <i>Add<\/i> method in our class, so for instance if we add<\/p>\n<pre lang=\"csharp\">\r\npublic class StatusMessages : IEnumerable<StatusMessage>\r\n{\r\n    \/\/ rest of the code omitted for brevity\r\n    public void Add(string text)\r\n    {\r\n         this.Add(new StatusMessage(text));\r\n    }\r\n    \/\/ rest of the code omitted for brevity\r\n}\r\n<\/pre>\n<p>we are able to use this syntax<\/p>\n<pre lang=\"csharp\">\r\nvar messagesAddStringInitializer = new StatusMessages\r\n            {\r\n                \"y\",\r\n                \"x\"\r\n            };\r\n<\/pre>\n<p>In addition it is even possible to use a mix of <i>Add<\/i> overloads<\/p>\n<pre lang=\"csharp\">\r\nvar messagesAddAndTextInitializers = new StatusMessages\r\n            {\r\n                new StatusMessage(\"y\"),\r\n                \"x\"\r\n            };\r\n<\/pre>\n<p><i>Add<\/i> method can also have multiple arguments<\/p>\n<pre lang=\"csharp\">\r\npublic class StatusMessages : IEnumerable<StatusMessage>\r\n{\r\n    \/\/ rest of the code omitted for brevity\r\n    public void Add(int statusCode, string text)\r\n    {\r\n        this.Add(new StatusMessage(text) { StatusCode = statusCode });\r\n    }\r\n    \r\n    public void Add(int statusCode, string text, string sourceSystem)\r\n    {\r\n        this.Add(new StatusMessage(text) { StatusCode = statusCode,SourceSystem = sourceSystem });\r\n    }\r\n    \/\/ rest of the code omitted for brevity\r\n}\r\n<\/pre>\n<p>in that case we are able to use this syntax<\/p>\n<pre lang=\"csharp\">\r\nvar messagesMultipleArgumentsInitializers = new StatusMessages\r\n            {\r\n                { 1, \"x\" },\r\n                {1,\"x\",\"source\" }\r\n            };\r\n<\/pre>\n<p>The last thing I would like to point out is that <i>Add<\/i> function doesn&#8217;t have to be an instance method, we can easily implement it as an extension method and still leverage the collection initializer syntax. <\/p>\n<pre lang=\"csharp\">\r\nnamespace AbusingCollectionInitializers\r\n{\r\n    public static class StatusMessagesExtensions\r\n    {\r\n        public static void Add(this StatusMessages statusMessages, int statusCode)\r\n        {\r\n            statusMessages.Add(new StatusMessage() { StatusCode = statusCode });\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>Now with proper namespace import we can write this code<\/p>\n<pre lang=\"csharp\">\r\nusing AbusingCollectionInitializers;\r\n\/\/ rest of the code omitted for brevity\r\nvar messagesExtensionInitializers = new StatusMessages { 1,2,3 };\r\n<\/pre>\n<p>Source code for this post can be found <a href=\"https:\/\/github.com\/tpodolak\/Blog\/tree\/master\/AbusingCollectionInitializers\">here<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Most of .NET developers are familiar with collection initializers syntax. Long story short, this language feature allows you to replace this ugly syntax var numbers = new List(); numbers.Add(1); numbers.Add(2); numbers.Add(3); numbers.Add(4); with much shorter and cleaner one var numbers = new List { 1, 2, 3, 4 }; The more interesting thing is the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,6],"tags":[160,162],"class_list":["post-579","post","type-post","status-publish","format-standard","hentry","category-net","category-net-4-0","tag-net","tag-net-4-0"],"_links":{"self":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/579","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/comments?post=579"}],"version-history":[{"count":6,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/579\/revisions"}],"predecessor-version":[{"id":586,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/579\/revisions\/586"}],"wp:attachment":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/media?parent=579"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/categories?post=579"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/tags?post=579"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}