C# Features

Last Updated: 12/2/2023

Array

Declaration

string[] languages; // one-dimensional
int[,] cells; // two-dimensional

Assignment

string[] languages = {"C#", "Java", "TypeScript", "Python", "JavaScript"};
string[] languages = new string[] {"C#", "Java", "TypeScript", "Python", "JavaScript"};
string[] languages = new [] {"C#", "Java", "TypeScript", "Python", "JavaScript"};

Size

  • The array size in the initialization statement and the number of elements contained within the curly braces must match.
string[] languages = new string[5];
string[] languages = new string[5] {"C#", "Java", "TypeScript", "Python", "JavaScript"};

Accessing Array

From Beginning

Console.WriteLine(languages[0]) //first element
Console.WriteLine(languages[1]) //second element
Console.WriteLine(languages[languages.Length - 1]) //last element

From End - C# 8

Console.WriteLine(languages[^1]) //from last 1st element
Console.WriteLine(languages[^2]) //from last 2st element
Console.WriteLine(languages[^languages.Length]); //first element

Ranges/Slicing

  • Extracting a slice of an array into a new array.
  • Range operator identifies the items by specifying the first (inclusive) up to the end (exclusive).
  • Specifying either the beginning index or “up to” (the end) index is optional,
string[] languages = new [] {"C#", "Java", "TypeScript", "Python", "JavaScript"};		
Console.WriteLine(string.Join(", ", languages[0..2]));
Console.WriteLine(string.Join(", ", languages[1..]));
Console.WriteLine(string.Join(", ", languages[..2]));
Console.WriteLine(string.Join(", ", languages[^3..^0]));
Console.WriteLine(string.Join(", ", languages[^3..]));
Console.WriteLine(string.Join(", ", languages[..^1]));
Console.WriteLine(string.Join(", ", languages[..]));

System.Index

  • indices and ranges are first-class types in .NET/C#
  • The System.Index type has two properties, a Value of type int, and an IsFromEnd property of type bool.
 System.Index index = ^42.

System.Range

  • System.Range has two properties, Start and End.
System.Range range = ..^0 
  • C# enables you to write custom collections that support ranges and the “from the end” indices.