× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

There are many ways to create objects in C#

James Jensen
Oct 14, 2014
<p> </p><p>C# has a lot of syntax sugar that makes it easy to create new objects. There's the plain vanilla, Java-style way:</p><pre><code class="language-cs">var request = new RequestModel(); request.search = "foo"; request.filters = new Dictionary&lt;string, string&gt;(); request.filters.Add("gender", "male");</code></pre><p>Or you can use object initializer syntax:</p><pre><code class="language-cs">var request = new RequestModel { search = "foo", filters = new Dictionary&lt;string, string&gt; { {"gender", "male"} } };</code></pre><p>In fact, if you're just creating an object for one-time use (to serialize to JSON, or use internally within your method, e.g.), you can just create an anonymous type and avoid writing class declarations:</p><pre><code class="language-cs">var request = new { search = "foo", filters = new { "gender" = "male" } };</code></pre><p> </p>
comments powered by Disqus