Collections in C#: A Better Alternative to Arrays for Handling Large Data Groups
C# is a simple, object-oriented programming language developed by Microsoft. The language runs on the Microsoft .NET framework. C# can be used to make client-server apps, XML based web apps and services, components that can be reused, database apps and Windows client applications. C# is inspired from the C family of languages, like C and C++, and by Java. The Common Language Runtime (CLR) component of .NET provides a great degree of functionality and support to C#. It works as a intermediary of sorts between C# and your computer. The code written in C# is first translated to Intermediate Language (IL) code and then compiled and executed by CLR. CLR also performs garbage collection and memory management functions, as well as exception handling. You don’t have to write extra code for these functions, like you have to do in other languages. Learn more about C# and the .NET framework with this course. This is quite a comprehensive course and shows you all the techniques you need to know to develop great .NET apps.
In this tutorial, we’re going to take a look at the different collection types and collection classes in C#. We’re assuming you have some knowledge of C#. If you’re new to C# or programming in general, you can sign up for our C# course if you want to learn the language in a fun and easy way.
What are collections in C#?
There are two ways you can manage a group of objects in C#: through arrays and through collections. Arrays are somewhat limited in functionality, however, because you have to declare the size of an array before you can use it. They cannot shrink or grow to match the size of your objects. If you run out of space, you have to create a new array. It’s also difficult to retrieve a single object from an array, in most cases.
Collections, on the other hand, are much more flexible than arrays. They will grow (or shrink) to match the number of your objects, if necessary. Some types of collections in C# let you assign keys to your object, which makes it easy to retrieve an object when necessary. The .NET framework provides several collection classes that can be used for different occasions, and can handle different types of objects. It also provides methods that let you add elements, remove elements, compare collections and query collections for elements, among other useful things.
You can explore more about arrays and collections in C# with this course.
Collection Types in C#
Collection classes are just like a normal class in C#. To add an object to the class, you have to declare a new collection, just like you would with a normal class. There are four major types of collection classes that are common for C# and Visual Basic (another language that runs with .NET). Let’s take a look.
- System.Collections.Generic Classes: Generic collection classes are used when you have to work with a single type of object. Objects of a different data type cannot be added to a generic collection. Generic collection classes enforce type safety. You don’t need to check the data type or convert data types if you use this collection. Generic classes are probably the safest and the most efficient collection classes in C#. For a complete list of available generic classes, see the official documentation.
- System.Collections.Concurrent Classes: C# supports the concept of multithreading. When multiple threads (multiple processes) are working on a collection, concurrent collection classes should be used. For a list of the different concurrent classes, check the official documentation.
- System.Collections Classes: System collection classes store objects as objects of type Object. For a full list of system classes, check here.
- Visual Basic Collection Class: Visual Basic Collection Classes let you add items on any data type. Type safety isn’t enforced. All elements are treated as objects belonging to the Object type. For a complete list of the classes in the VB Collection, go here.
You won’t encounter most of the classes that are present in these different collections until you begin to develop some serious applications. To learn more about classes, data types and objects, you can sign up for this comprehensive C# course.
Generic Collection Classes
There are numerous generic collection classes in the .NET framework with different uses. We’ll take a look at the classes you’ll encounter most often when writing C# programs:
- Dictionary: The dictionary type stores keys and value pairs. The dictionary type is used to fill hasthables in C#. You can retrieve your data very quickly if it uses the dictionary type.
- LinkedList and SortedList: The LinkedList class stores doubly linked data. The SortedList class stores data by keys – that is, the keys decide how the data is sorted in the class.
- Stack: You may have encountered a stack in Java before. The stack class stores objects following the last-in, first-out (LIFO) convention.
- Queue: Queues, like stacks, are also present in Java. The queue class stores objects following the first-in, first-out (FIFO) convention.
- Hashtable: The hashtable class stores elements with keys and values in a hash table. It lets you create a hash table in C#.
- HashSet: The HashSet class can be used to eliminate duplicate elements in C#.
- BitArray: This is class that lets you create bit data, that is, binary data. The data is stored in an array type of collection, though the collection is more flexible than an array.
Using the Collection Classes in a Program
We’ll just write a small, simple program to demonstrate one of the classes (hashtable) in action:
// Invoking the System.Collections class using System.Collections; using System; class Exampleclassprogram { static void Main() { // Creating a hash table using the hashtable collection class Hashtable hash = new Hashtable(); hash[1] = "Nine"; hash[3] = "Five"; foreach (DictionaryEntry entry in hash) { Console.WriteLine("{0} : {1}", entry.Key, entry.Value); } } } Output: 3: Five 1: Nine
Notice that we invoked the System.Collection type of collection in this program. While it’s okay to use this collection in this case, for general purpose code you’re better off invoking the System.Collection.Generic type. We’ve created a simple hash table (named hash) using the hashtable class. We’ve also used the Dictionary type in the program. As you can see, it stores a key and value pair in the hash table, which we print in the output.
You will be using a lot of collections even if you intend to create a basic application in C, so it’s a good idea to get acquainted with the different collection types and classes, and their methods. You can take this advanced C# course and for a more in depth treatment.
C sharp is a true object-oriented programming language – that is, it supports polymorphism, inheritance and encapsulation. It’s powerful, flexible and dynamic. Microsoft has poured millions of dollars into developing and promoting C#, and many of its newest products and services (Windows 8 apps, ASP.NET and Silverlight) use C# to a great extent. C#, in fact, may become the greatest contender to Sun’s Java in the future. It’s definitely worth your time to learn this language. And if you’re in a crunch, this 1 hour C# course may just be the thing for you!
Recommended Articles
Top courses in C# (programming language)
C# (programming language) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.