C# Is Modern and Easy
C# Is Modern and Easy
C# is versatile
C# is a Swiss army knife. While most programming languages were designed for a specific purpose, C#
was designed to do C#. We can use C# to build today’s modern software applications. C# can be used
to develop all kind of applications including Windows client apps, components and libraries, services
and APIs, Web applications, Mobile apps, cloud applications, and video games.
Here is a list of types of applications C# can build,
C# is evolving
C# 8.0 is the latest version of C#. If you look at C# language history, C# is evolving faster than any
other languages. Thanks to Microsoft and a strong community support. C# was initially designed to
write Windows client applications but today, C# can do pretty much anything from console apps, cloud
app, and modern machine learning software.
The following table summarizes the C# versions with year and features.
Version Year Features
1999- Modern, Object Oriented, Simple, Flexible, Typesafe, Managed, Garbage Collection,
1.0
2002 Cross-platform
2.0 2005 Generics, Anonymous Method, Partial Class, Nullable Type
3.0 2008 LINQ, Lamda Expression, Extension Method, Anonymous Type, Var
4.0 2010 Named and Optional Parameters, Dynamic Binding
5.0 2012 Async Programming
Compiler-as-a-service (Roslyn), Exception filters, Await in catch/finally blocks, Auto
6.0 2015 property initializers, Dictionary initializer, Default values for getter-only properties,
Expression-bodied members. Null propagator, String interpolation, nameof operator
Tuples, Out variables, Pattern matching, Deconstruction, Local functions, Digit
separators, Binary literals, Ref returns and locals, Generalized async return types,
7.0 2017
Expression bodied constructors and finalizers, Expression bodied getters and setters,
Throw can also be used as expression
7.1 2017 Async main, Default literal expressions, Inferred tuple element names
Reference semantics with value types, Non-trailing named arguments, Leading
7.2 2017
underscores in numeric literals, private protected access modifier
Accessing fixed fields without pinning, Reassigning ref local variables, Using
7.3 2018 initializers on stackalloc arrays, Using fixed statements with any type that supports a
pattern, Using additional generic constraints
Nullable reference types, Async streams, ranges and indices, default implementation of
8.0 2019
interface members, recursive patterns, switch expressions, target-type new expressions
C# Strings
In any programming language, to represent a value, we need a data type. The Char data type represents
a character in .NET. In .NET, the text is stored as a sequential read-only collection of Char data types.
There is no null-terminating character at the end of a C# string; therefore, a C# string can contain any
number of embedded null characters ('\0').
The System. String data type represents a string in .NET. A string class in C# is an object of type
System. String. The String class in C# represents a string.
The following code creates three strings with a name, number, and double values.
1. // String of characters
2. System.String authorName = "Mahesh Chand";
3.
4. // String made of an Integer
5. System.String age = "33";
6.
7. // String made of a double
8. System.String numberString = "33.23";
Here is the complete example that shows how to use stings in C# and .NET.
1. using System;
2. namespace CSharpStrings
3. {
4. class Program
5. {
6. static void Main(string[] args)
7. {
8. // Define .NET Strings
9. // String of characters
10. System.String authorName = "Mahesh Chand";
11.
12. // String made of an Integer
13. System.String age = "33";
14.
15. // String made of a double
16. System.String numberString = "33.23";
17.
18. // Write to Console.
19. Console.WriteLine("Name: {0}", authorName);
20. Console.WriteLine("Age: {0}", age);
21. Console.WriteLine("Number: {0}", numberString);
22. Console.ReadKey();
23. }
24. }
25. }
String class defined in the .NET base class library represents text as a series of Unicode characters. The
String class provides methods and properties to work with strings.
The String class has methods to clone a string, compare strings, concatenate strings, and copy strings.
This class also provides methods to find a substring in a string, find the index of a character or
substrin.g, replace characters, split a string, trim a string, and add padding to a string. The string class
also provides methods to convert a string's characters to uppercase or lowercase.
C# Arrays
An Array in C# is a collection of objects or types. C# Array elements can be of any type, including an
array type. An array can be Single-Dimensional, Multidimensional or Jagged. A C# Array can be
declared as fixed length or dynamic. An Array in C# can be a single dimension, multi dimension, or a
jagged array. Learn how to work with arrays in C#.
In C#, an array index starts at zero. That means the first item of an array starts at the 0 thposition. The
position of the last item on an array will total number of items - 1. So if an array has 10 items, the last
10th item is at 9th position.
In C#, arrays can be declared as fixed length or dynamic. A fixed length array can store a predefined
number of items. A dynamic array does not have a predefined size. The size of a dynamic
array increases as you add new items to the array. You can declare an array of fixed length or dynamic.
You can even change a dynamic array to static after it is defined.
Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest
dynamic array of integer types that do not have a fixed size.
int[] intArray;
As you can see from the above code snippet, the declaration of an array starts with a type of array
followed by a square bracket ([]) and name of the array.
The following code snippet declares an array that can store 5 items only starting from index 0 to 4.
1. int[] intArray;
2. intArray = new int[5];
The following code snippet declares an array that can store 100 items starting from index 0 to 99.
1. int[] intArray;
2. intArray = new int[100];
C# Collections
C# collection types are designed to store, manage and manipulate similar data more efficiently. Data
manipulation includes adding, removing, finding, and inserting data in the collection. Collection types
implement the following common functionality:
.NET supports two types of collections, generic collections and non-generic collections. Prior to .NET
2.0, it was just collections and when generics were added to .NET, generics collections were added as
well.
Learn More C#
C# Corner has thousands of tutorials, code samples, and articles on C# programming. Here is a list of
some of the most popular C# programming topics,
C# Books
C# Corner provides several C# language programming books. Here are a few:
Summary
This tutorial is an introduction to C# language for beginners. In this tutorial, we learned how to write
our first C# program, basics of data types, classes, objects, and class members.
C# array a collection of objects or types. C# array elements can be of any type, including other array
types. An array can be Single-Dimensional, Multidimensional, or Jagged. The Array class in C#
represents an array. This tutorial is an introduction to array and how to use arrays in C#. The tutorial
also discusses various methods and properties of C# Array class.
In C#, an array index starts at zero. That means the first item of an array starts at the 0th position. The
position of the last item on an array will the total number of items - 1. So if an array has 10 items, the
last 10th item is in 9th position.
In C#, arrays can be declared as fixed-length or dynamic. A fixed-length array can store a predefined
number of items. A dynamic array does not have a predefined size. The size of a dynamic
array increases as you add new items to the array. You can declare an array of fixed length or dynamic.
You can even change a dynamic array to static after it is defined.
Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest
dynamic array of integer types that do not have a fixed size.
int[] intArray;
C#
Copy
As you can see from the above code snippet, the declaration of an array starts with a type of array
followed by a square bracket ([]) and the name of the array.
The following code snippet declares an array that can store 5 items only starting from index 0 to 4.
int[] intArray;
The following code snippet declares an array that can store 100 items starting from index 0 to 99.
int[] intArray;
In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an
array, you need to instantiate an array by using the "new" operator.
The following code snippet defines arrays of double, char, bool, and string data types.
The following code snippet creates an array of 3 items and values of these items are added when the
array is initialized.
Alternative, we can also add array items one at a time as listed in the following code snippet.
// Initialize a fixed array one item at a time
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;
C#
Copy
The following code snippet declares a dynamic array with string values.
string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar",
"Dinesh Beniwal" };
C#
Copy
Accessing Array in C#
We can access an array item by passing the item index in the array. The following code snippet creates
an array of three items and displays those items on the console.
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;
Console.WriteLine(staticIntArray[0]);
Console.WriteLine(staticIntArray[1]);
Console.WriteLine(staticIntArray[2]);
C#
Copy
This method is useful when you know what item you want to access from an array. If you try to pass an
item index greater than the items in array, you will get an error.
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"Dinesh Beniwal"
};
Console.WriteLine(str);
}
C#
Copy
This approach is used when you do not know the exact index of an item in an array and needs to loop
through all the items.
Array Types in C#
Arrays can be divided into the following four categories.
Single-dimensional arrays
Multidimensional arrays or rectangular arrays
Jagged arrays
Mixed arrays.
The following code declares an integer array that can store 3 items. As you can see from the code, first I
declare the array using [] bracket and after that, I instantiate the array by calling the new operator.
int[] intArray;
Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not
initialized, its items are automatically initialized to the default initial value for the array type if the array
is not initialized at the time it is declared.
The following code declares and initializes an array of three items of integer type.
You can even directly assign these values without using the new operator.
string[,] mutliDimStringArray;
C#
Copy
The following code snippet is an example of fixed-sized multi-dimensional arrays that defines two
multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array
can store 4 items. Both of these arrays are initialized during the declaration.
Now let's see examples of multi-dimensional dynamic arrays where you are not sure of the number of
items of the array. The following code snippet creates two multi-dimensional arrays with no limit.
int[, ] numbers = {
1,
},
3,
},
5,
};
string[, ] names = {
"Rosy",
"Amy"
},
"Peter",
"Albert"
};
C#
Copy
We can also initialize the array items one item at a time. The following code snippet is an example of
initializing array items one at a time.
numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;
C#
Copy
Multi-dimensional array items are represented in a matrix format and to access its items, we need to
specify the matrix dimension. For example, item(1,2) represents an array item in the matrix in the
second row and third column.
The following code snippet shows how to access numbers array defined in the above code.
Console.WriteLine(numbers[0, 0]);
Console.WriteLine(numbers[0, 1]);
Console.WriteLine(numbers[1, 0]);
Console.WriteLine(numbers[1, 1]);
Console.WriteLine(numbers[2, 0]);
Console.WriteLine(numbers[2, 2]);
C#
Copy
Jagged Arrays in C#
Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.
Declaration of a jagged array involves two brackets. For example, the following code snippet declares a
jagged array that has three items of an array.
The following code snippet declares a jagged array that has two items of an array.
We can also initialize a jagged array's items by providing the values of the array's items. The following
code snippet initializes item an array's items directly during the declaration.
2,
12
};
4,
14,
24,
34
};
6,
16,
26,
36,
46,
56
};
C#
Copy
Console.Write(intJaggedArray3[0][0]);
Console.WriteLine(intJaggedArray3[2][5]);
C#
Copy
We can also loop through all of the items of a jagged array. The Length property of an array helps a lot;
it gives us the number of items in an array. The following code snippet loops through all of the items of
a jagged array and displays them on the screen.
System.Console.WriteLine();
}
C#
Copy
Mixed Arrays in C#
Mixed arrays are a combination of multi-dimension arrays and jagged arrays. The mixed arrays type is
removed from .NET 4.0. I have not really seen any use of mixed arrays. You can do anything you want
with the help of multi-dimensional and jagged arrays.
A Simple Example
Here is a complete example listed in Listing 1 that demonstrates how to declare all kinds of arrays then
initialize them and access them.
To test this code, create a console application using Visual Studio 2010 or Visual C# Express and copy
and paste this code.
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"Dinesh Beniwal"
};
Console.WriteLine(str);
Console.WriteLine("-----------------------------");
"Rosy",
"Amy"
}, {
"Peter",
"Albert"
};
Console.WriteLine(str);
Console.WriteLine("-----------------------------");
int[][] intJaggedArray3 = {
new int[] {
2,
12
},
new int[] {
14,
14,
24,
34
},
new int[] {
6,
16,
26,
36,
46,
56
};
Console.Write($"Element({i}): ");
Console.Write($"{intJaggedArray3[i][j]} ");
Console.WriteLine();
Console.WriteLine("-----------------------------");
C#
Copy
Listing 1
C# Array Class
Array class in C# is the mother of all arrays and provides functionality for creating, manipulating,
searching, and sorting arrays in .NET Framework.
Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an
abstract base class that means we cannot create an instance of the Array class.
Creating an Array
Array class provides the CreateInstance method to construct an array. The CreateInstance method takes
the first parameter as the type of items and the second and third parameters are the dimension and their
range. Once an array is created, we use the SetValue method to add items to an array.
The following code snippet creates an array and adds three items to the array. As you can see the type
of the array items is a string and the range is 3. You will get an error message if you try to add 4th item
to the array.
Note: Calling SetValue on an existing item of an array overrides the previous item value with the new
value.
Console.WriteLine(ival);
}
C#
Copy
Listing 2
C# Array Properties
Table 1
The code snippet in Listing 3 creates an array and uses Array properties to display property values.
0,
1,
};
if (intArray.IsFixedSize) {
Console.WriteLine($"Size : {intArray.Length.ToString()}");
Console.WriteLine($"Rank : {intArray.Rank.ToString()}");
}
C#
Copy
Listing 3
Note
You must sort an array before searching. See the comments in this article.
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
// Find an item
Listing 4
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
// Find an item
Console.WriteLine();
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
Console.WriteLine(str);
Console.WriteLine();
Console.WriteLine("Sorted Array");
Console.WriteLine("---------------------");
Array.Sort(stringArray);
Console.WriteLine(str);
}
C#
Copy
Listing 5
Alternatively, the Sort method takes the starting index and number of items after that index. The
following code snippet sorts 3 items starting at 2nd position.
Array.Sort(stringArray, 2, 3);
C#
Copy
Figure 4
The GetValue and SetValue methods of the Array class can be used to get and set values of an array's
items. The code listed in Listing 4 creates a 2-dimensional array instance using the CreateInstance
method. After that, I use the SetValue method to add values to the array.
In the end, I find a number of items in both dimensions and use GetValue method to read values and
display on the console.
names.SetValue("Rosy", 0, 0);
names.SetValue("Amy", 0, 1);
names.SetValue("Peter", 0, 2);
names.SetValue("Albert", 0, 3);
names.SetValue("Mel", 1, 0);
names.SetValue("Mongee", 1, 1);
names.SetValue("Luma", 1, 2);
names.SetValue("Lara", 1, 3);
Listing 6
Figure 5
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
Console.WriteLine(str);
Console.WriteLine();
Console.WriteLine("Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
// Array.Sort(stringArray, 2, 3);
Console.WriteLine(str);
Console.WriteLine();
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
// Array.Sort(stringArray, 2, 3);
Console.WriteLine(str);
}
C#
Copy
Listing 7
Array.Clear(stringArray, 1, 2);
C#
Copy
Note
Keep in mind, the Clear method does not delete items. Just clear the values of the items.
The code listed in Listing 8 clears two items from the index 1.
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
Console.WriteLine(str);
}
Console.WriteLine();
Console.WriteLine("Clear Items");
Console.WriteLine("---------------------");
Array.Clear(stringArray, 1, 2);
Console.WriteLine(str);
}
C#
Copy
Listing 8
The output of Listing 8 generates Figure 7. As you can see from Figure 7, the values of two items from
the output are missing but actual items are there.
Figure 7
Console.WriteLine(stringArray.GetLength(0).ToString());
Console.WriteLine(stringArray.GetLowerBound(0).ToString());
Console.WriteLine(stringArray.GetUpperBound(0).ToString());
C#
Copy
Copy an array in C#
The Copy static method of the Array class copies a section of an array to another array. The CopyTo
method copies all the elements of an array to another one-dimension array. The code listed in Listing 9
copies contents of an integer array to an array of object types.
oddArray.SetValue(1, 0);
oddArray.SetValue(3, 1);
oddArray.SetValue(5, 2);
oddArray.SetValue(7, 3);
oddArray.SetValue(9, 4);
Listing 9
You can even copy a part of an array to another array bypassing the number of items and starting item
in the Copy method. The following format copies a range of items from an Array starting at the
specified source index and pastes them to another Array starting at the specified destination index.
Strings are one of the most important data types in any modern language including C#. In this article,
you will learn how to work with strings in C#. The article discusses the String class, its methods and
properties and how to use them.
1. C# String
In any programming language, to represent a value, we need a data type. The Char data type represents
a character in .NET. In .NET, the text is stored as a sequential read-only collection of Char data types.
There is no null-terminating character at the end of a C# string; therefore a C# string can contain any
number of embedded null characters ('\0').
The System.String data type represents a string in .NET. A string class in C# is an object of type
System.String. The String class in C# represents a string.
The following code creates three strings with a name, number, and double values.
// String of characters
Here is the complete example that shows how to use stings in C# and .NET.
using System;
namespace CSharpStrings
class Program
// Write to Console.
Console.ReadKey();
}
C#
Copy
2. .NET String Class
String class defined in the .NET base class library represents text as a series of Unicode characters. The
String class provides methods and properties to work with strings.
The String class has methods to clone a string, compare strings, concatenate strings, and copy strings.
This class also provides methods to find a substring in a string, find the index of a character or
substring, replace characters, split a string, trim a string, and add padding to a string. The string class
also provides methods to convert a string's characters to uppercase or lowercase.
Check out these links to learn about a specific operation or functionality of strings.
The String class is equivalent to the System.String in C# language. The string class also inherits all the
properties and methods of the System.String class.
4. Create a string
There are several ways to construct strings in C# and .NET.
The String class has several overloaded constructors that take an array of characters or bytes. The
following code snippet creates a string from an array of characters.
Console.WriteLine(name);
C#
Copy
You simply define a string type variable and assign a text value to the variable by placing the text value
without double quotes. You can put almost any type of characters within double quotes accept some
special character limitations.
The following code snippet defines a string variable named firstName and then assigns text value
Mahesh to it.
string firstName;
firstName = "Mahesh";
C#
Copy
using System;
namespace CSharpStrings
class Program
Console.ReadKey();
}
C#
Copy
5. Create a string using concatenation
Sting concatenation operator (+) can be used to combine more than one string to create a single string.
The following code snippet creates two strings. The first string adds a text Date and current date value
from the DateTime object. The second string adds three strings and some hard coded text to create a
larger string.
string authorDetails = firstName + " " + lastName + " is " + age + " years old.";
Console.WriteLine(nowDateTime);
Console.WriteLine(authorDetails);
C#
Copy
Here is a detailed article on string concatenation - Six Effetive Ways To Concatenate Strings In C#.
Console.WriteLine(authorInfo);
C#
Copy
Console.WriteLine(authorInfo);
C#
Copy
9. Get all characters of a string using C#
A string is a collection of characters.
The following code snippet reads all characters of a string and displays on the console.
Console.WriteLine(nameString[counter]);
C#
Copy
10. Get size of string
The Length property of the string class returns the number of characters in a string including white
spaces.
The following code snippet returns the size of a string and displays on the console.
Console.WriteLine(nameString);
The following code snippet uses the Replace method to remove empty characters and then displays the
non-empty characters of a string.
Console.WriteLine(nameWithoutEmptyChar[counter]);
C#
Copy
12. Convert String to Char Array
ToCharArray method converts a string to an array of Unicode characters. The following code snippet
converts a string to char array and displays them.
Console.WriteLine(ch);
}
C#
Copy
13. What is an empty string
An empty string is a valid instance of a System.String object that contains zero characters. There are
two ways to create an empty string. We can either use the string.Empty property or we can simply
assign a text value with no text in it.
An empty string is sometimes used to compare the value of other strings. The following code snippet
uses an empty string to compare with the name string.
if (name != empStr)
Console.WriteLine(name);
}
C#
Copy
In real-world coding, we will probably never create an empty string unless you plan to use it
somewhere else as a non-empty string. We can simply use the string.Empty direct to compare a string
with an empty string.
if (name != string.Empty)
{
Console.WriteLine(name);
}
C#
Copy
if (name != empStr)
Console.WriteLine(name);
if (name != string.Empty)
Console.WriteLine(name);
}
C#
Copy
14. Understanding Null Strings in C#
A null string is a string variable that has not been initialized yet and has a null value. If you try to call
any methods or properties of a null string, you will get an exception. A null string valuable is exactly
the same as any other variable defined in your code.
A null string is typically used in string concatenation and comparison operations with other strings.
}
C#
Copy
15. Summary
In this article, we learned the basics of strings in C# and .NET and how to use the String class available
in .NET in our code. Here are some more similar articles related to strings in .NET with C#.
Exception handling in C#, suppoted by the try catch and finaly block is a mechanism to detect and
handle run-time errors in code. The .NET framework provides built-in classes for common exceptions.
The exceptions are anomalies that occur during the execution of a program. They can be because of
user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these
anomalies, the .NET runtime environment provide a default mechanism, which terminates the program
execution.
try..catch..finally
C# provides three keywords try, catch and finally to implement exception handling. The try encloses the
statements that might throw an exception whereas catch handles an exception if one exists. The finally
can be used for any cleanup work that needs to be done.
Try..catch..finally block example:
1. try
2. {
3. // Statement which can cause an exception.
4. }
5. catch(Type x)
6. {
7. // Statements for handling the exception
8. }
9. finally
10. {
11. //Any cleanup code
12. }
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later
to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either with one or more
catch blocks or a finally block or with both catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally block. We
can say that the statements inside the finally block is executed always. Note that it is an error to transfer
control out of a finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class
for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can
create their own exception classes, provided that this should inherit from either Exception class or one
of the standard derived classes of Exception class like DivideByZeroExcpetion to ArgumentException
etc.
Uncaught Exceptions
The following program will compile but will show an error during execution. The division by zero is a
runtime anomaly and program terminates with an error message. Any uncaught exceptions in the
current context propagate to a higher context and looks for an appropriate catch block to handle it. If it
can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the
execution of the entire program.
1. //C#: Exception Handling
2. //Author: rajeshvs@msn.com
3. using System;
4. class MyClient
5. {
6. public static void Main()
7. {
8. int x = 0;
9. int div = 100/x;
10. Console.WriteLine(div);
11. }
12. }
The modified form of the above program with exception handling mechanism is as follows. Here we are
using the object of the standard exception class DivideByZeroException to handle the exception caused
by division by zero.
1. //C#: Exception Handling
2. using System;
3. class MyClient
4. {
5. public static void Main()
6. {
7. int x = 0;
8. int div = 0;
9. try
10. {
11. div = 100 / x;
12. Console.WriteLine("This linein not executed");
13. }
14. catch (DivideByZeroException)
15. {
16. Console.WriteLine("Exception occured");
17. }
18. Console.WriteLine($"Result is {div}");
19. }
20. }
1. //C#: Exception Handling
2. using System;
3. class MyClient
4. {
5. public static void Main()
6. {
7. int x = 0;
8. int div = 0;
9. try
10. {
11. div = 100/x;
12. Console.WriteLine("Not executed line");
13. }
14. catch(DivideByZeroException)
15. {
16. Console.WriteLine("Exception occured");
17. }
18. finally
19. {
20. Console.WriteLine("Finally Block");
21. }
22. Console.WriteLine($"Result is {div}");
23. }
24. }
Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.
1. //C#: Exception Handling
2. using System;
3. class MyClient
4. {
5. public static void Main()
6. {
7. int x = 0;
8. int div = 0;
9. try
10. {
11. div = 100/x;
12. Console.WriteLine("Not executed line");
13. }
14. finally
15. {
16. Console.WriteLine("Finally Block");
17. }
18. Console.WriteLine($"Result is {div}");
19. }
20. }
But in this case, since there is no exception handling catch block, the execution will get terminated. But
before the termination of the program statements inside the finally block will get executed. In C#, a try
block must be followed by either a catch or finally block.
Multiple Catch Blocks
A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember
that more specialized catch block should come before a generalized one. Otherwise the compiler will
show a compilation error.
1. //C#: Exception Handling: Multiple catch
2. using System;
3. class MyClient
4. {
5. public static void Main()
6. {
7. int x = 0;
8. int div = 0;
9. try
10. {
11. div = 100 / x;
12. Console.WriteLine("Not executed line");
13. }
14. catch (DivideByZeroException de)
15. {
16. Console.WriteLine("DivideByZeroException");
17. }
18. catch (Exception)
19. {
20. Console.WriteLine("Exception");
21. }
22. finally
23. {
24. Console.WriteLine("Finally Block");
25. }
26. Console.WriteLine($"Result is {div}");
27. }
28. }
1. //C#: Exception Handling: Handling all exceptions
2. using System;
3. class MyClient
4. {
5. public static void Main()
6. {
7. int x = 0;
8. int div = 0;
9. try
10. {
11. div = 100 / x;
12. Console.WriteLine("Not executed line");
13. }
14. catch
15. {
16. Console.WriteLine("oException");
17. }
18. Console.WriteLine($"Result is {div}");
19. }
20. }
1. //C#: Exception Handling: Handling all exceptions
2. using System;
3. class MyClient
4. {
5. public static void Main()
6. {
7. int x = 0;
8. int div = 0;
9. try
10. {
11. div = 100 / x;
12. Console.WriteLine("Not executed line");
13. }
14. catch (Exception)
15. {
16. Console.WriteLine("oException");
17. }
18. Console.WriteLine($"Result is {div}");
19. }
20. }
Throwing an Exception
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this
purpose. The general form of throwing an exception is as follows.
1. throw exception_obj;
1. throw new ArgumentException("Exception");
2.
3. //C#: Exception Handling:
4. using System;
5. class MyClient
6. {
7. public static void Main()
8. {
9. try
10. {
11. throw new DivideByZeroException("Invalid Division");
12. }
13. catch (DivideByZeroException)
14. {
15. Console.WriteLine("Exception");
16. }
17. Console.WriteLine("LAST STATEMENT");
18. }
19. }
Re-throwing an Exception
The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the
keyword throw inside the catch block. The following program shows how to do this.
1. //C#: Exception Handling: Handling all exceptions
2. using System;
3. class MyClass
4. {
5. public void Method()
6. {
7. try
8. {
9. int x = 0;
10. int sum = 100 / x;
11. }
12. catch (DivideByZeroException)
13. {
14. throw;
15. }
16. }
17. }
18. class MyClient
19. {
20. public static void Main()
21. {
22. MyClass mc = new MyClass();
23. try
24. {
25. mc.Method();
26. }
27. catch (Exception)
28. {
29. Console.WriteLine("Exception caught here");
30. }
31. Console.WriteLine("LAST STATEMENT");
32. }
33. }
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and exceptions
generated by the common language runtime. System.Exception is the base class for all exceptions in
C#. Several exception classes inherit from this class including ApplicationException and
SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions
that derive directly from System.Exception include IOException, WebException etc.
The common language runtime throws SystemException. The ApplicationException is thrown by a user
program rather than the runtime. The SystemException includes the ExecutionEngineException,
StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good
programming practice to throw SystemExceptions in our applications.
System.OutOfMemoryException
System.NullReferenceException
Syste.InvalidCastException
Syste.ArrayTypeMismatchException
System.IndexOutOfRangeException
System.ArithmeticException
System.DevideByZeroException
System.OverFlowException
User-defined Exceptions
In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for
all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or
one of its standard derived classes.
1. //C#: Exception Handling: User defined exceptions
2. using System;
3. class MyException : Exception
4. {
5. public MyException(string str)
6. {
7. Console.WriteLine("User defined exception");
8. }
9. }
10. class MyClient
11. {
12. public static void Main()
13. {
14. try
15. {
16. throw new MyException("RAJESH");
17. }
18. catch (Exception)
19. {
20. Console.WriteLine("Exception caught here" + e.ToString());
21. }
22. Console.WriteLine("LAST STATEMENT");
23. }
24. }
Design Guidelines
Exceptions should be used to communicate exceptional conditions. Don't use them to communicate
events that are expected, such as reaching the end of a file. If there's a good predefined exception in the
System namespace that describes the exception condition-one that will make sense to the users of the
class-use that one rather than defining a new exception class and put specific information in the
message. Finally, if code catches an exception that it isn't going to handle, consider whether it should
wrap that exception with additional information before re-throwing it.
Object-oriented programming (OOP) is the core ingredient of the .NET framework. OOP is so
important that, before embarking on the road to .NET, you must understand its basic principles and
terminology to write even a simple program. The fundamental idea behind OOP is to combine into a
single unit both data and the methods that operate on that data; such units are called an object. All OOP
languages provide mechanisms that help you implement the object-oriented model. They are
encapsulation, inheritance, polymorphism and reusability. Let's now take a brief look at these concepts.
1. OOP's overview
2. Classes and Objects
3. Constructor and Destructor
4. Function Overloading
5. Encapsulation
6. Inheritance
7. Interface
8. Polymorphism
Encapsulation
Encapsulation binds together code and the data it manipulates and keeps them both safe from outside
interference and misuse. Encapsulation is a protective container that prevents code and data from being
accessed by other code defined outside the container.
Inheritance
Inheritance is the process by which one object acquires the properties of another object. A type derives
from a base type, taking all the base type members fields and functions. Inheritance is most useful when
you need to add functionality to an existing type. For example all .NET classes inherit from the
System.Object class, so a class can include new functionality as well as use the existing object's class
functions and properties as well.
Polymorphism
Polymorphism is a feature that allows one interface to be used for a general class of action. This
concept is often expressed as "one interface, multiple actions". The specific action is determined by the
exact nature of circumstances.
Reusability
Once a class has been written, created and debugged, it can be distributed to other programmers for use
in their own program. This is called reusability, or in .NET terminology this concept is called a
component or a DLL. In OOP, however, inheritance provides an important extension to the idea of
reusability. A programmer can use an existing class and without modifying it, add additional features to
it.
This simple one-class console "Hello world" program demonstrates many fundamental concepts
throughout this article and several future articles.
using System;
namespace oops
//class definition
Console.WriteLine("Hello World!");
}
}
C#
Copy
So SimpleHelloWorld is the name of the class that contains the Main () method. On line 1 , a using
directive indicates to the compiler that this source file refers to classes and constructs declared within
the System namespace. Line 6 with the public keyword indicates the program accessibility scope for
other applications or components.
At line 7 there appears an opening curly brace ("{") which indicates the beginning of the
SimpleHelloWorld class body. Everything belongs to the class, like fields, properties and methods
appear in the class body between the opening and closing braces. The purpose of the Main () method is
to provide an entry point for application execution.
The static keyword in the Main () method states that this method would be executed without
instantiating the class.
You can compile a C# program into either an assembly or a module. If the program has one class that
contains a Main () method then it can be compiled directly into an assembly. This file has an ".exe"
extension. A program with no Main() method can be compiled into a module as in the following:
You can then compile this program by F9 or by simply running the C# command line compiler
(csc.exe) against the source file as the following:
csc oops.cs
A class declaration consists of a class header and body. The class header includes attributes, modifiers,
and the class keyword. The class body encapsulates the members of the class, that are the data members
and member functions. The syntax of a class declaration is as follows:
Attributes provide additional context to a class, like adjectives; for example the Serializable attribute.
Accessibility is the visibility of the class. The default accessibility of a class is internal. Private is the
default accessibility of class members. The following table lists the accessibility keywords;
Keyword Description
public Public class is visible in the current and referencing assembly.
private Visible inside current class.
protected Visible inside current and derived class.
Internal Visible inside containing assembly.
Internal protected Visible inside containing assembly and descendent of thecurrent class.
Modifiers refine the declaration of a class. The list of all modifiers defined in the table are as follows;
Modifier Description
sealed Class can't be inherited by a derived class.
static Class contains only static members.
unsafe The class that has some unsafe construct likes pointers.
Abstract The instance of the class is not created if the Class is abstract.
The baselist is the inherited class. By default, classes inherit from the System.Object type. A class can
inherit and implement multiple interfaces but doesn't support multiple inheritances.
4. You can also write your own code in the default program.cs file that is created but it is a good
programming practice to create a new class.
5. For adding a new class, right-click over the project name (oops) in the Solution Explorer, then
click "Add" > "Class". Give the name to the class "customer" as in the following;
When you open the customer.cs class. you will find some default-generated code as in the following,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace oops
class customer
}
C#
Copy
Note
The C# console application project must require a single entry point Main () function that is already
generated in the program class. For example if you add a new customer class and want to define one or
more Main () entry points here then .NET will throw an error of multiple entry points. So it is advisable
to delete or exclude the program.cs file from the solution.
So here in this example the customer class defines fields such as CustID, Name and Address to hold
information about a particular customer. It might also define some functionality that acts upon the data
stored in these fields.
using System;
namespace oops
class customer
// Member Variables
customer()
CustID=1101;
Name="Tom";
Address="USA";
Console.WriteLine("Customer="+CustID);
Console.WriteLine("Name="+Name);
Console.WriteLine("Address="+Address);
}
}
C#
Copy
At line 9, we are defining a constructor of the customer class for initializing the class member fields.
The constructor is a special function that is automatically called when the customer class object is
created (instantiated). And at line 11 we are printing these fields to the console by creating a user
defined method displayData().
You can then instantiate an object of this class to represent one specific customer, set the field value for
that instance and use its functionality, as in:
class customer
//Entry point
// object instantiation
//Method calling
obj.displayData();
//fields calling
Console.WriteLine(obj.CustID);
Console.WriteLine(obj.Name);
Console.WriteLine(obj.Address);
}
C#
Copy
Here you use the keyword new to declare the customer class instance. This keyword creates the object
and initializes it. When you create an object of the customer class, the .NET framework IDE provides a
special feature called Intellisense that provides access to all the class member fields and functions
automatically. This feature is invoked when the "." operator is put right after the object, as in the
following;
Normally, as the program grows in size and the code becomes more complex, the Intellisense feature
increases the convenience for the programmer by showing all member fields, properties and functions.
using System;
namespace oops
class Program
Console.WriteLine("Main class");
dObj.addition();
class demo
int x = 10;
int y = 20;
int z;
z = x + y;
Console.WriteLine(z);
}
C#
Copy
Here in this example, we are creating an extra class "demo" in the program.cs file at line 12 and finally
we are instantiating the demo class with the program class inside the Main() entry in lines 6 to 11. So it
doesn't matter how many classes we are defining in a single assembly.
Partial classes
Typically, a class will reside entirely in a single file. However, in situations where multiple developers
need access to the same class, then having the class in multiple files can be beneficial. The partial
keywords allow a class to span multiple source files. When compiled, the elements of the partial types
are combined into a single assembly.
There are some rules for defining a partial class as in the following;
A partial type must have the same accessibility.
If the partial type is sealed or abstract then the entire class will be sealed and abstract.
In the following example we are adding two files, partialPart1.cs and partialPart2.cs, and declare a
partial class, partialclassDemo, in both classes.
partialPart1.cs
using System;
namespace oops
}
C#
Copy
partialPart2.cs
using System;
namespace oops
}
}
}
C#
Copy
And finally we are creating an instance of the partialclassDemo in the program.cs file as the following:
Program.cs
using System;
namespace oops
class Program
obj.method1();
obj.method2();
}
C#
Copy
Static classes
A static class is declared using the "static" keyword. If the class is declared as static then the compiler
never creates an instance of the class. All the member fields, properties and functions must be declared
as static and they are accessed by the class name directly not by a class instance object.
using System;
namespace oops
{
//static fields
//static method
y = x * x;
Console.WriteLine(y);
staticDemo.calcute();
}
C#
Copy
Creating and accessing Class Component Library
.NET provides the capability of creating libraries (components) of a base application rather than an
executable (".exe"). Instead the library project's final build version will be ".DLL" that can be
referenced from other outside applications to expose its entire functionality.
Step-by-step tutorial
using System;
namespace LibraryUtil
public MathLib() { }
int z = x + y;
Console.WriteLine(z);
double z = Math.Sqrt(x);
Console.WriteLine(z);
}
}
C#
Copy
Build this code and you will notice that a DLL file was created, not an executable, in the root directory
of the application (path = D:\temp\LibraryUtil\LibraryUtil\bin\Debug\ LibraryUtil.dll).
Now create another console based application where you utilize all the class library's functionality.
Then you have to add the class library dll file reference to access the declared class in the library dll.
(Right-click on the Reference then "Add reference" then select the path of the dll file.)
When you add the class library reference then you will notice in the Solution Explorer that a new
LibraryUtil is added as in the following;
Now add the namespace of the class library file in the console application and create the instance of the
class declared in the library as in the following;
using System;
namespace oops
obj.calculareSum(2, 5);
obj.calculareSqrt(25);
}
C#
Copy
Classes with no constructor have an implicit constructor called the default constructor, that is
parameterless. The default constructor assigns default values to fields.
A constructor returns void but does not have an explicitly declared return type.
Classes can have multiple constructors in the form of default, parameter or both.
using System;
namespace oops
class customer
// Member Variables
Console.WriteLine(Name);
//Entry point
// object instantiation
//Method calling
obj.AppendData();
}
C#
Copy
Note
Static Constructor
A constructor can be static. You create a static constructor to initialize static fields. Static constructors
are not called explicitly with the new statement. They are called when the class is first referenced. There
are some limitations of the static constructor as in the following;
using System;
namespace oops
class customer
// Member Variables
static customer()
x = 10;
Console.WriteLine(x);
//Entry point
customer.getData();
}
C#
Copy
Destructors
The purpose of the destructor method is to remove unused objects and resources. Destructors are not
called directly in the source code but during garbage collection. Garbage collection is nondeterministic.
A destructor is invoked at an undetermined moment. More precisely a programmer can't control its
execution; rather it is called by the Finalize () method. Like a constructor, the destructor has the same
name as the class except a destructor is prefixed with a tilde (~). There are some limitations of
destructors as in the following;
The following implements a destructor and dispose method. First of all we are initializing the fields via
constructor, doing some calculations on that data and displaying it to the console. But at line 9 we are
implementing the destructor that is calling a Dispose() method to release all the resources.
using System;
namespace oops
class customer
// Member Variables
public int x, y;
customer()
Console.WriteLine("Fields inititalized");
x = 10;
y = x * x;
Console.WriteLine(y);
Console.WriteLine("Fields cleaned");
x = 0;
y = 0;
//destructor
~customer()
Dispose();
//Entry point
//instance created
obj.getData();
}
C#
Copy
At line 12 when the instance is created, fields are initialized but it is not necessary that at the same time
the destructor is also called. Its calling is dependent on garbage collection. If you want to see the
destructor being called into action then put a breakpoint (by F9) at line 10 and compile the application.
The CLR indicates its execution at the end of the program by highlighting line 10 using the yellow
color.
Function Overloading
Function overloading allows multiple implementations of the same function in a class. Overloaded
methods share the same name but have a unique signature. The number of parameters, types of
parameters or both must be different. A function can't be overloaded on the basis of a different return
type alone.
using System;
namespace oops
class funOverload
//overloaded functions
name = last;
//Entry point
obj.setName("barack");
}
C#
Copy
At lines 3, 4 and 5 we are defining three methods with the same name but with different parameters. In
the Main (), the moment you create an instance of the class and call the functions setName() via obj at
lines 7, 8 and 9 then intellisense will show three signatures automatically.
Encapsulation
Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both
safe from outside interference and misuse. In OOP, code and data may be combined in such a way that
a self-contained box is created. When code and data are linked together in this way, an object is created
and encapsulation exists.
Within an object, code, data or both may be private or public to that object. Private code is known to
and accessible only by another part of the object, that is private code or data may not be accessible by a
piece of the program that exists outside the object. When the code and data is public, other portions of
your program may access it even though it is defined within an object.
using System;
namespace oops
class Encapsulation
/// <summary>
/// Every member Variable and Function of the class are bind
/// with the Encapsulation class object only and safe with
/// </summary>
// Encapsulation Begin
int x;
//class constructor
public Encapsulation(int iX)
this.x = iX;
int Calc = x * x;
Console.WriteLine(Calc);
// End of Encapsulation
//Entry point
//instance created
obj. MySquare();
}
C#
Copy
Inheritance
Inheritance is the process by which one object can acquire the properties of another object. Inheritance
is a "is a kind of" relationship and it supports the concept of classification in which an object needs only
define those qualities that make it unique within the class. Inheritance involves a base class and a
derived class. The derived class inherits from the base class and also can override inherited members as
well as add new members to extend the base class.
A base type represents the generalization, whereas a derived type represents a specification of an
instance. Such as Employees that can have diverse types, such as hourly, salaried and temporary so in
that case Employees is the general base class and hourly, salaried and temporary employee are
specialized derived classes.
Classes can inherit from a single class and one or more interfaces. When inheriting from a class, the
derived class inherits the members including the code of the base class. The important point to
remember is that Constructors and Destructors are not inherited from the base class.
For example we are defining two classes, Father and Child. You notice at line 7, we are implementing
inheritance by using a colon (:); at this moment all the properties belonging to the Father Class is
accessible to the Child class automatically.
using System;
namespace oops
//Base Class
}
//Derived class
class Inheritance
//Entry point
fObj.FatherMethod();
cObj.FatherMethod();
cObj.ChildMethod();
}
C#
Copy
At line 11 , the Intellisense only shows the Father class functions but at line 15 to 16 the Child class
object is able to access both class methods as in the following.
We can create a class in the VB.Net language or another .NET supported language and can inherit them
in a C# .Net class and vice versa. But a class developed in C++ or other unmanaged environment can't
be inherited in .NET.
Note
Accessibility
Accessibility sets the visibility of the member to outside assemblies or derived types. The following
table describes member accessibility;
So the base keyword refers to the base class constructor, while parameterlist2 determines which
overloaded base class constructor is called.
In the following example, the Child class's constructor calls the single-argument constructor of the base
Father class;
using System;
namespace oops
//Base Class
//constructor
public Father()
}
public void FatherMethod()
//Derived class
public Child()
: base()
class Inheritance
//Entry point
cObj.FatherMethod();
cObj.ChildMethod();
Console.ReadKey();
}
}
}
C#
Copy
At line 4, we are defining a base Father Class constructor and in the derived class Child, at line 8 we are
initializing it explicitly via base keyword. If we pass any parameter in the base class constructor then
we have to provide them in the base block of the child class constructor.
Virtual Methods
By declaring a base class function as virtual, you allow the function to be overridden in any derived
class. The idea behind a virtual function is to redefine the implementation of the base class method in
the derived class as required. If a method is virtual in the base class then we have to provide the
override keyword in the derived class. Neither member fields nor static functions can be declared as
virtual.
using System;
namespace oops
class myBase
//virtual function
}
class virtualClass
// class instance
new myDerived().VirtualMethod();
Console.ReadKey();
}
C#
Copy
Hiding Methods
If a method with the same signature is declared in both base and derived classes, but the methods are
not declared as virtual and overriden respectively, then the derived class version is said to hide the base
class version. In most cases, you would want to override methods rather than hide them.
Otherwise .NET automatically generates a warning.
In the following example, we are defining a VirutalMethod() in the myBase class but not overriding it
in the derived class, so in that case the compiler will generate a warning. The compiler will assume that
you are hiding the base class method. So to overcome that problem, if you prefix the new keyword in
the derived class method then the compiler will prefer the most derived version method. You can still
access the base class method in the derived class by using the base keyword.
using System;
namespace oops
class myBase
//virtual function
}
class myDerived : myBase
base.VirtualMethod();
class virtualClass
// class instance
new myDerived().VirtualMethod();
Console.ReadKey();
}
C#
Copy
Abstract Classes
C# allows both classes and functions to be declared abstract using the abstract keyword. You can't
create an instance of an abstract class. An abstract member has a signature but no function body and
they must be overridden in any non-abstract derived class. Abstract classes exist primarily for
inheritance. Member functions, properties and indexers can be abstract. A class with one or more
abstract members must be abstract as well. Static members can't be abstract.
In this example, we are declaring an abstract class Employess with a method displayData() that does not
have an implementation. Then we are implementing the displayData() body in the derived class. One
point to be noted here is that we have to prefixe the abstract method with the override keyword in the
derived class.
using System;
namespace oops
//abstract class
//derived class
class abstractClass
// class instance
new test().displayData();
}
C#
Copy
Sealed Classes
Sealed classes are the reverse of abstract classes. While abstract classes are inherited and are refined in
the derived class, sealed classes cannot be inherited. You can create an instance of a sealed class. A
sealed class is used to prevent further refinement through inheritance.
Suppose you are a developer of a class library and some of the classes in the class library are extensible
but other classes are not extensible so in that case those classes are marked as sealed.
using System;
namespace oops
void myfunv();
}
C#
Copy
Interface
An interface is a set of related functions that must be implemented in a derived class. Members of an
interface are implicitly public and abstract. Interfaces are similar to abstract classes. First, both types
must be inherited; second, you cannot create an instance of either. Although there are several
differences as in the following;
So the question is, which of these to choose? Select interfaces because with an interface, the derived
type still can inherit from another type and interfaces are more straightforward than abstract classes.
using System;
namespace oops
// interface
void methodA();
void methodB();
Console.WriteLine("methodA");
Console.WriteLine("methodB");
class interfaceDemo
obj.methodA();
obj.methodB();
}
C#
Copy
void methodA();
void methodB();
void methodC();
}
C#
Copy
Polymorphism
Polymorphism is the ability to treat the various objects in the same manner. It is one of the significant
benefits of inheritance. We can decide the correct call at runtime based on the derived type of the base
reference. This is called late binding.
In the following example, instead of having a separate routine for the hrDepart, itDepart and
financeDepart classes, we can write a generic algorithm that uses the base type functions. The method
LeaderName() declared in the base abstract class is redefined as per our needs in 2 different classes.
using System;
namespace oops
Console.WriteLine("Mr. jone");
}
Console.WriteLine("Mr. Tom");
Console.WriteLine("Mr. Linus");
class PolymorphismDemo
obj1.LeaderName();
obj2.LeaderName();
obj3.LeaderName();
Console.ReadKey();
}
C#
Copy
.NET
C#
Object Oriented Programming
OOP
<
The switch case statement in C# is a selection statement. It executes code of one of the conditions based
on a pattern match with the specified match expression. The switch statement is an alternate to using the
if..else statement when there are more than a few options. The code examples in this article demonstrate
various usages of switch..case statement in C# and .NET Core.
The switch statement pairs with one or more case blocks and a default block. The case block of code is
executed for the matching value of switch expression value. If the switch value doesn’t match the case
value, the default option code is executed.
The following is the definition of the switch..case statement.
1. switch (expression)
2. {
3. case expression_value1:
4. Statement
5. break;
6. case expression_value2:
7. Statement
8. break;
9. case expression_value3:
10. Statement
11. break;
12. default:
13. Statement
14. break;
15. }
1. // Generate a random value between 1 and 9
2. int caseSwitch = new Random().Next(1, 9);
3. switch (caseSwitch)
4. {
5. case 1:
6. Console.WriteLine("Case 1");
7. break;
8. case 2:
9. Console.WriteLine("Case 2");
10. break;
11. case 3:
12. Console.WriteLine("Case 3");
13. break;
14. default:
15. Console.WriteLine("Value didn’t match earlier.");
16. break;
17. }
Listing 1.
The case statement can be a statement of one or multiple statements or nested statements.
Listing 2 uses multiple statements in case 1.
1. switch (caseSwitch)
2. {
3. case 1:
4. Console.WriteLine("Case 1");
5. DateTime date = DateTime.Today;
6. Console.WriteLine("Today's date is {0}", date);
7. if (date.Day == 2)
8. {
9. Console.WriteLine("This is the shortest month");
10. }
11. break;
12. case 2:
13. Console.WriteLine("Case 2");
14. break;
15. case 3:
16. Console.WriteLine("Case 3");
17. break;
18. default:
19. Console.WriteLine("Default case");
20. break;
21. }
Listing 2.
Using Enum in a switch statement
Let’s find if today is a week end or a week day. Listing 3 uses an enum in a case statement and checks
if the DayOfWeek is Saturday or Sunday, it’s a weekend, else it’s a work day.
1. // switch..case with enum
2. void WeekEndOrWeekDay()
3. {
4. switch (DateTime.Now.DayOfWeek)
5. {
6. case DayOfWeek.Saturday:
7. case DayOfWeek.Sunday:
8. Console.WriteLine("Today is Weekend");
9. break;
10. default:
11. Console.WriteLine("Today is a work day.");
12. break;
13. }
14. }
Listing 3.
Using multiple case in one switch
You can execute the same code for multiple switch expression values. In Listing 4 example, if the value
is Color.Blue, Color.Black, Color.Orange, or default, the last line of code is executed.
1. public enum Color { Red, Green, Blue, Black, Orange }
2. public static void RandomConsoleBackground()
3. {
4. Color c = (Color)(new Random()).Next(0, 4);
5. switch (c)
6. {
7. case Color.Red:
8. Console.BackgroundColor = ConsoleColor.Red;
9. Console.Clear();
10. Console.WriteLine("Red");
11. break;
12. case Color.Green:
13. Console.BackgroundColor = ConsoleColor.Green;
14. Console.Clear();
15. Console.WriteLine("Green");
16. break;
17. case Color.Blue:
18. case Color.Black:
19. case Color.Orange:
20. default:
21. Console.WriteLine("No need to change background.");
22. break;
23. }
Listing 4.
Case Patterns
The case statement defines a pattern to match the match expression. There are two types of patterns,
constant pattern, and non-constant (type) pattern.
Constant pattern
The constant pattern tests whether the match expression equals a specified constant. In case of a
constant pattern, the case statement is followed by a constant value.
1. case constant:
where constant is the value to test for and can be any of the following constant expressions,
If match expression and constant are integral types, the equality operator ‘==’ is used to
compare the value and returns true for the matching value.
Otherwise, the value of the expression is determined by a call to the static Object.Equals
method.
1. // switch..case with char
2. void CharSwitchCase()
3. {
4. char ch = 'c';
5. switch (ch)
6. {
7. case 'c':
8. Console.WriteLine("c found!");
9. break;
10. default:
11. Console.WriteLine("c not found!");
12. break;
13. }
14. }
Listing 5.
Listing 6 is an example of using a string constant in a switch statement.
1. // switch..case with string
2. void StringSwitchCase()
3. {
4. string name = "Mahesh";
5. switch (name)
6. {
7. case "Mahesh":
8. Console.WriteLine("First name was used!");
9. break;
10. case "Chand":
11. Console.WriteLine("Last name was used!");
12. break;
13. default:
14. Console.WriteLine("No name found!");
15. break;
16. }
17. }
Listing 6.
Type Pattern
The switch statement can use a type as an expression.
1. case type varname
where type is the name of the type to which the result of expr is to be converted, and varname is the
object to which the result of expr is converted if the match succeeds.
The following code example in Listing 7 uses a type to compare with an enum, an Array, and a List as
an expression in the switch..case statement.
1. using System;
2. using System.Collections;
3. using System.Collections.Generic;
4. public class Author
5. {
6. string name;
7. string book;
8. int year;
9. public Author(string Name, string Book, int Year)
10. {
11. this.name = Name;
12. this.book = Book;
13. this.year = Year;
14. }
15. }
16. public enum Color { Red, Green, Blue, Black, Orange }
17. class SwitchCaseExample{
18. static void Main(string[] args)
19. {
20. // Pass an Enum
21. SwitchCaseWithTypePatternSample(Color.Red);
22. // Pass an Array
23. string[] names = {"Mahesh Chand", "Allen O'neill", "David McCarter"};
24. SwitchCaseWithTypePatternSample(names);
25. // Pass a List
26. List<Author> authors = new List<Author>();
27. authors.Add(new Author("Mahesh Chand", "ADO.NET Programming", 2002));
28. SwitchCaseWithTypePatternSample(authors);
29. Console.ReadKey();
30. }
31. public static void SwitchCaseWithTypePatternSample(object type)
32. {
33. switch (type)
34. {
35. case Enum e:
36. switch (e)
37. {
38. case Color.Red:
39. Console.BackgroundColor = ConsoleColor.Red;
40. Console.WriteLine("Red");
41. break;
42. case Color.Green:
43. Console.BackgroundColor = ConsoleColor.Green;
44. Console.Clear();
45. Console.WriteLine("Green");
46. break;
47. case Color.Blue:
48. case Color.Black:
49. case Color.Orange:
50. default:
51. Console.WriteLine("No need to change background.");
52. break;
53. }
54. break;
55. case Array a:
56. Console.WriteLine($"Number of items in array: {a.Length}");
57. break;
58. case IList list:
59. Console.WriteLine($"Number of items in list: {list.Count}");
60. break;
61. default:
62. Console.WriteLine("default");
63. break;
64. }
65. }
66. }
Listing 7.
Summary
This article and code examples demonstrates various use cases of C# switch..case statement.