This page looks best with JavaScript enabled

Inline Initializing C# Lists - Quick Tip

 ·   ·  ☕ 1 min read

C# includes a method for initializing Lists that means you do not need to repeatedly Add("foo") throughout your code. This allows you to specify a set of items immediately after the Lists constructor that causes the items to be sequentially added to the list after its created for you. This works for most collection types including Arrays and Lists.

Here’s an example of what constructing a list like this might look like.

1
2
// Note: replace angled brackets with correct character!
var myList = new Liststring() { "this", "is", "a", "test" };

Doing this traditionally would look like this:

1
2
3
4
5
6
// Note: replace angled brackets with correct character!
var myList = new Liststring();
myList.Add("this");
myList.Add("is");
myList.Add("a");
myList.Add("test");

This trick also works with Dictionary’s! Here’s how: https://youtu.be/lFsgmxzw7IU

Join the World of Zero Discord server: https://discord.gg/hU5Kq2u


Sam Wronski
WRITTEN BY
Sam Wronski
Maker of things and professional software engineer. Lets make something awesome together!