Welcome to the next unit of this course!
Before we get deeper into C# essentials for interview prep, we'll remind ourselves about some C# features — specifically, C# collections like arrays
and strings
. These collections allow C# to group multiple elements, such as numbers or characters, under a single entity.
Some of these concepts might already be familiar to you, so you can breeze through the beginning until we get to the meat of the course and the path.
As our starting point, it's crucial to understand what C# collections are. They help us manage multiple values efficiently and are categorized into Arrays
, Dictionaries
, and more.
We will focus mainly on arrays and strings in C#.
Arrays in C# are fixed-size collections, meaning once an array is defined, its size cannot be changed directly. However, you can use methods like Array.Resize()
to create a new array with a different size while preserving the elements of the original array, or manually copy elements with Array.Copy()
. While the size is fixed, the array itself is mutable, allowing you to modify its individual elements after creation.
C#1// Example of an array 2int[] numbers = { 1, 2, 3, 4, 5 };
On the other hand, strings in C# are immutable, meaning once a string is created, it cannot be changed. Any operations that seem to modify a string, such as concatenation or replacing characters, actually result in the creation of a new string object in memory.
C#1// Example of a string 2string greeting = "Hello"; 3
Let's see mutability/immutability in action for arrays and strings.
C#1using System; 2 3class MainClass { 4 public static void Main() { 5 // Defining an array and a string 6 int[] myArray = {1, 2, 3, 4}; 7 string myString = "hello"; 8 9 // Now let's try to change the first element of both these collections 10 myArray[0] = 100; // Works 11 12 // Uncommenting the below line will throw an error 13 // myString[0] = 'H'; // Uncommenting this will cause a compilation error as strings are immutable 14 } 15}
Think about managing a list of tasks or inventory items. Without a collection like an array, it would be hard to keep track of multiple values efficiently. In C#, arrays allow us to store items where each has a specific index, making it easy to access or modify them.
Working with Arrays
is as simple as this:
C#1using System; 2 3class MainClass { 4 public static void Main() { 5 // Creating an array 6 string[] fruits = { "apple", "banana", "cherry" }; 7 8 // Modifying an element (since it's a fixed-size collection, we can't add items but we can modify existing ones) 9 fruits[0] = "apricot"; // ["apricot", "banana", "cherry"] 10 11 // Accessing elements using indexing 12 string firstFruit = fruits[0]; // "apricot" 13 string lastFruit = fruits[fruits.Length - 1]; // "cherry" 14 15 // Resizing the array 16 Array.Resize(ref fruits, 5); // Increases array size to 5 17 // The new elements are initialized to null by default 18 fruits[3] = "date"; 19 fruits[4] = "elderberry"; 20 21 // Copying the array 22 string[] copiedFruits = new string[5]; 23 Array.Copy(fruits, copiedFruits, 5); 24 25 // Display the resized array elements 26 for (int i = 0; i < fruits.Length; i++) 27 { 28 if (fruits[i] != null) { 29 Console.WriteLine(fruits[i]); // Outputs each fruit including new elements 30 } 31 } 32 33 Console.WriteLine("Copied Fruits:"); 34 for (int i = 0; i < copiedFruits.Length; i++) 35 { 36 if (copiedFruits[i] != null) { 37 Console.WriteLine(copiedFruits[i]); // Outputs each fruit from the copied array 38 } 39 } 40 } 41}
In the example above, Array.Resize(ref fruits, 5)
changes the size of the fruits
array to 5. The ref
keyword is used to pass the array by reference, allowing the method to modify its size. Note that when an array is resized to a larger size, the new elements are initialized to null
by default.
Array.Copy(fruits, copiedFruits, 5)
is used to copy the contents of the fruits
array to the copiedFruits
array.
Think of strings
as sequences of letters or characters. So, whether you're writing down a message or noting a paragraph, it all boils down to a string
in C#. Strings
are enclosed by double quotes.
C#1using System; 2 3class MainClass { 4 public static void Main() { 5 // Creating a string 6 string greetingString = " Hello, world! "; 7 8 // Accessing characters using indexing 9 char firstChar = greetingString[0]; // ' ' 10 char lastChar = greetingString[greetingString.Length - 1]; // ' ' 11 12 // Making the entire string lowercase 13 string lowercaseGreeting = greetingString.ToLower(); // " hello, world! " 14 15 // Making the entire string uppercase 16 string uppercaseGreeting = greetingString.ToUpper(); // " HELLO, WORLD! " 17 18 // Removing leading and trailing whitespace 19 string trimmedGreeting = greetingString.Trim(); // "Hello, world!" 20 21 // Display the results 22 Console.WriteLine(greetingString); // " Hello, world! " 23 Console.WriteLine(lowercaseGreeting); // " hello, world! " 24 Console.WriteLine(uppercaseGreeting); // " HELLO, WORLD! " 25 Console.WriteLine(trimmedGreeting); // "Hello, world!" 26 } 27}
-
ToLower()
: Converts all characters in the string to lowercase.- Example:
"Hello, WORLD!".ToLower()
results in"hello, world!"
.
- Example:
-
ToUpper()
: Converts all characters in the string to uppercase.- Example:
"Hello, world!".ToUpper()
results in"HELLO, WORLD!"
.
- Example:
-
Trim()
: Removes all leading and trailing whitespace from the string.- Example:
" Hello, world! ".Trim()
results in"Hello, world!"
.
- Example:
Though strings
are immutable, we can use these methods to effectively work with them. These methods create a new string
for us.
Both arrays
and strings
allow us to access individual elements through indexing. In C#, we start counting from 0, implying the first element is at index 0, the second at index 1, and so on. Negative indexing is not directly supported in C#.
We have many operations we can perform on our arrays
and strings
. We can slice them, concatenate them, repeat them, and even find the occurrence of a particular element!
C#1using System; 2using System.Linq; 3 4class Program { 5 static void Main() { 6 // Define an array and a string 7 int[] myArray = {1, 2, 3, 4, 5}; 8 string myString = "Hello"; 9 10 // Slicing (substring for strings, range for arrays) 11 int[] sliceArray = myArray[2..4]; // [3, 4] 12 string sliceString = myString.Substring(1, 2); // "el" 13 14 // Concatenation 15 int[] concatenatedArray = myArray.Concat(new int[] {6, 7}).ToArray(); // [1, 2, 3, 4, 5, 6, 7] 16 string concatenatedString = myString + " world!"; // "Hello world!" 17 18 // Searching for an element 19 int indexInArray = Array.IndexOf(myArray, 3); // 2 20 int indexInString = myString.IndexOf('l'); // 2 21 22 // Sorting the array in descending order 23 int[] sortedArray = myArray.OrderByDescending(x => x).ToArray(); // [5, 4, 3, 2, 1] 24 25 // Output the results (minimized output) 26 Console.WriteLine(string.Join(", ", sliceArray)); // 3, 4 27 Console.WriteLine(sliceString); // el 28 Console.WriteLine(string.Join(", ", concatenatedArray)); // 1, 2, 3, 4, 5, 6, 7 29 Console.WriteLine(indexInArray); // 2 30 Console.WriteLine(indexInString); // 2 31 Console.WriteLine(string.Join(", ", sortedArray)); // 5, 4, 3, 2, 1 32 } 33}
And there we have it, a C# toolkit of arrays
and strings
!
Give yourself a pat on the back! You've navigated through C# collections, primarily focusing on arrays
and strings
, and learning how to create, access, and manipulate them via various operations.
Up next, reinforce your understanding with plenty of hands-on practice. The comprehension of these concepts, combined with frequent practice, will enable you to tackle more complex problem statements with ease. Happy coding!