Learn the most popular objects, methods and operators of the C# programming language
C# is an object-oriented high-level programming language developed by Microsoft. This language is cross-platform and powerful so it is very popular, widespread and used in many programming fields. C# is used for the development of web, desktop, and mobile applications, games, and services.
C# is an easy-to-use programming language that is being improved all the time. It contains a lot of useful objects, methods, expressions and operators. In this article, we are going to learn the most popular ones.
C# List
One of the most widely used collections in C# is List<T>. It contains a list of elements of a given type.
The advantage of a List<T> in C# is that you can add items to it dynamically as needed. You do not need to immediately allocate a certain amount of memory for all the elements in the list. Memory is allocated automatically as needed. This is very convenient when you do not know in advance the size of the list you need.
In the following example, we create a list of 4 books and print their names and authors.
You can initialize a list immediately while creating (as in our example) or create an empty list and add elements to it using a special method.
public class Book
{
public string Name { get; set; }
public string Author { get; set; }
public Book(string name, string author)
{
Name = name;
Author = author;
}
}
public class Program
{
public static void Main(string[] args)
{
List<Book> books = new List<Book>
{
{ new Book(“Leaving Time”, “Jodi Picoult”) },
{ new Book(“1st to Die”, “James Patterson”) },
{ new Book(“Three”, “Ted Dekker”) },
{ new Book(“Mr. Mercedes”, “Stephen King”) }
};
foreach (Book b in books)
Console.WriteLine(b.Name + ” ” + b.Author);
}
}
/////////////////////////////////////////////
Output
Leaving Time Jodi Picoult
1st to Die James Patterson
Three Ted Dekker
Mr. Mercedes Stephen King
/////////////////////////////////////////////
Class List<T> contains a lot of methods for inserting and removing items, searching, sorting, etc. Let’s see examples of some of them.
For adding a new item to the list use the method Add(T item).
books.Add(new Book(“Name”, “Author”));
You can use a method FindAll(Predicate<T> match) to find all items with specified characteristics in the list.
List<Book> search = books.FindAll(b => b.Author.StartsWith(“J”));
foreach (Book s in search)
Console.WriteLine(s.Name + ” ” + s.Author);
//////////////////////////////////////////////////////
Output
Leaving Time Jodi Picoult
1st to Die James Patterson
//////////////////////////////////////////////////////
For deleting an element with a concrete index from the list use the method RemoveAt(int index).
books.RemoveAt(1).
C# Array
An array in C# contains elements of the same type. It is used for storing multiple values, that are similar, into one variable instead of creating a separate variable for each value. This storage method makes it easier to access and process variables.
When you initialize an array you should know how many elements it will contain and immediately allocate the amount of memory that these will occupy. The length of an array is fixed. Once the array is created, you cannot decrease or increase it.
Arrays in C# can be one-dimensional and multidimensional. Below are some examples of how you can create and initialize the one-dimensional array in C#.
int[] numbers = new int [] { 1, 2, 3, 4};
int[] numbers = new int [4];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
Now let’s look at the example of a multidimensional array. In this example we create a two-dimensional array with integers and display the number of elements in the second dimension and the rank of the array.
int[,] numbers = new int [,] {{ 1, 2, 3, 4}, {5, 6, 7, 8}};
Console.WriteLine(numbers.GetLength(1));
Console.WriteLine(numbers.Rank);
//////////////////////
Output
4
2
//////////////////////
Class Array contains methods for creating, searching, sorting arrays. In the following example, we create an array of strings with the names of car brands. The strings are sorted alphabetically ascending using method Sort(Array) of the class Array. Method BinarySearch(Array, Object) searches for the specified string and returns its index.
string[] cars = new string[] {“BMW”, “Infinity”, “Volvo”, “Mercedes”, “Ford”};
Array.Sort(cars);
foreach (string c in cars)
Console.WriteLine(c);
Console.WriteLine(Array.BinarySearch(cars, “Infinity”));
//////////////////////
Output
BMW
Ford
Infinity
Mercedes
Volvo
2
//////////////////////
Operators in C#
C# programming language has several groups of operators for working with data. Here are the most popular of them.
- Arithmetical: add (+), substruct (-), divide (/), multiply (*), remainder (%), increment (++), decrement (–).
- Comparison: equal (==), not equal (!=), less than (<), less than or equal (<=), greater than (>), greater than or equal (>=).
Arithmetical and comparison operators are used with operands of numeric types.
- Logical: negation (!), and (&&), or (||). They are used with bool operands.
- Assignment (=). It assigns the value of the right operand to the left one.
- Type-testing, castings (is, as, cast, typeof). These operators are used to check the type of operands and convert them to another type.
Special attention should be paid to the ternary and null-coalescing operators. Ternary operator (?:) is a logical operator that consists of three parts. The first part contains the condition, the second part contains the result if the condition is true, and the third one contains the result if the condition is false. Here is the syntax of the ternary operator.
condition ? result if true : result if false.
This operator is a shorter and more convenient form of the construction if-else.
string name = “Helen”;
string welcome = string.IsNullOrEmpty(name) ? “Hello, Madam!” : “Hello, ” + name;
/////////////////////////////////////////////
Output
Hello, Helen
////////////////////////////////////////////
Null-coalescing operators (??) checks if the left operand is null. If false, then it returns the value of the left operand, if true, then it returns the value of the right one. Operator ?= assigns the value of the right operand to the left one if the left operand is null.
Type conversion in C#
C# programming language makes it possible to convert data of one type to another type implicit or explicit. Implicit conversion does not require special syntax and usually succeeds without throwing exceptions. There are special methods in C# for explicitly converting data from one type to another. Let’s take a look at some examples of how you can convert a string to an int in C#. First, we use the method Parse(string value).
string str = “10”;
int i = int.Parse(str);
Console.WriteLine(i – 1);
////////////////////////////////////
Output
9
///////////////////////////////////
This method works correctly if the string can be converted to an int. Otherwise, an exception will be thrown. To avoid this situation you can use the method TryParse(string value, out int result). This method returns true if the value can be parsed and false in another way. The result is written to the out parameter.
string str = “10”;
int res;
if (int.TryParse(str, out res))
Console.WriteLine(res – 1);
else
Console.WriteLine(“Not an integer”);
Another way to convert a string to an int is to use the static method Convert.ToInt32(string value). This method is equivalent to the method int.Parse(string value).
C# Enum
Enum in C# is a type that is defined by a list of named logically related constants. A type of enum must be of one of the following: byte, int, short, long. If the enum type is not specified, then the int type is assigned to it by default. Each enum element is assigned by default an integer value starting from 0. You can also assign any other values manually. The enum keyword is used to declare an enum.
The next example shows an enum Colors that contains a list of different colors.
public enum Colors
{
White,
Blue,
Red,
Green,
Yellow,
Black
}
We can change it by giving each or only some colors a different number and specify enum type.
public enum Colors : byte
{
White = 250,
Blue = 10,
Red,
Green = 140,
Yellow,
Black
}
Constants that have not been assigned a value are filled automatically. Let’s see what the following code prints.
Console.WriteLine((byte)Colors.Red);
Console.WriteLine((byte)Colors.Yellow);
Console.WriteLine((byte)Colors.Black);
//////////////////////////////////////////
Output
11
141
142
///////////////////////////////////////
Conclusion
In this article, we examined the most popular objects, methods and operands in the C# programming language. They are used for both writing simple programs and more complex ones. For further training, we recommend you read about delegates and events in C#, using LINQ with data collections. Knowledge Pillars reveals that its (CSC) C# Coding Specialist, (DCS) .Net Coding Specialist, (JCS) Javascript Coding Specialist and (HCCS) HTML/CSS Coding Specialist will reach the market soon. If you’re looking to validate your existing C# skills sign up for updates.