Edentity Web Systems
You solve creative. We crack code.
/Header/WhoWeAre.jpg
 

07/27/2010 Shortcuts for initializing C# collections
Posted by Matthew Quinn

When initializing a collection to a known set of values, C# provides a bit of syntactic sugar to cut down on your typing. The long way to initialize a list of the first 5 primes might look like this:

List<int> primes = new List<int>();
primes.Add(2);
primes.Add(3);
primes.Add(5);
primes.Add(7);
primes.Add(11);
You can shorten this to:

List<int> primes = new List<int>() { 2, 3, 5, 7, 11 };
// Works for arrays too
int[] primes = new int[] { 2, 3, 5, 7, 11 };
There is a similar shortcut for dictionaries. This comes in handy when you're initializing a UGC Record:

Record blogPost = new Record() {
    ID = -1,
    RecordTypeName = "BlogPost",
    Values = new Dictionary<string, object>() {
        { "Title", "Example Post" },
        { "Body", "<p>This is the body of my post.</p>" },
        { "Date", DateTime.Now },
        { "ViewCount", 0 }
    }
};

 

« Back to Blog Main Page |

0 Comment(s)

Leave Comment

Name:
Comment:  
 
Security Check: 
 
 
Edentity Web Systems Inc.
Suite 201
40 Spadina Ave.
Toronto ON
M5V 2H8
Tel:
416.591.2500
Fax:
416.352.5270

From Our Blog

09/03/2010
Canonical Links Posted by Russell Huntington
08/31/2010
HTML5 In All its Glory! Posted by Chuck Lee
08/26/2010
Home | Who We Are | What We Do | Clients & Brands | Careers | Contact

Copyright © 2010 Edentity Web Systems Inc. Privacy Policy