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
|