DEV Community

Scott Slatton
Scott Slatton

Posted on

C# Generic Collections

One thing I’ve heard before and definitely am guilty of repeating before knowing the meaning of, is the statement: “Javascript doesn’t have arrays it has lists”. I’ve always understood this to basically mean nothing because “functionally, they’re the same” and when you’re learning Javascript for the first time, this can be a good philosophy to have because you don’t get bogged down with theory and can focus your attention on just building things. When I began delving into C# however, starting to use it on a daily basis, this philosophy caught up with me quickly. I’ve known for quite a long time that arrays in languages other than Javascript have a fixed length that you must declare at some point. It was incredibly intimidating and I struggled to understand how you work around this limitation. I’d like to share with you my “Aha!” moment I had when I finally understood that learning data structures and when to use them became so pivotal to creating proper, functional and optimized code.

C# has a namespace in the .NET library called System.Collections.Generic and it’s within here that you can find your lists, stacks, and queues. These are typically data structures you have to build out manually in Javascript. You can instantiate any of these like a normal object declaration.

List<T> grades = new List<T>();

Sidenote: If this is the first time you’re seeing the it’s a generic type parameter, meaning you can fill in that parameter with any type recognized by the compiler like string or double.

Lists do obviously come with a higher memory cost than normal arrays but solves our issue of needing to know how many items are going to be in our array if you’re not sure . My favorite thing about using these built in data structures is that they come with methods built in as well. You can easily implement a binary search on a list by calling .BinarySearch() on the List object instance.

Top comments (0)