SlideShare uma empresa Scribd logo
1 de 83
C# is a strongly typed object-oriented programming language. C# is open source, simple, modern,
flexible, and versatile. In this article, let us learn what C# is, what C# can do, and how C# is different
from C++ and other programming languages.
A programming language on computer science is a language that is used to write software programs.
C# is a programming language developed and launched by Microsoft in 2001. C# is a simple, modern,
and object-oriented language that provides modern day developers flexibility and features to build
software that will not only work today but will be applicable for years in the future.
Key characteristics of C# language include:
1. Modern and easy
2. Fast and open source
3. Cross platform
4. Safe
5. Versatile
6. Evolving
C# is modern and easy
C# is a simple, modern, and an object-oriented programming language. The purpose of C# was to develop
a programming language that is not only easy to learn but also supports modern day functionality for all
kind of software development.
If you look at the history of programming languages and their features, each programming language was
designed for a specific purpose to solve a specific need at that time.
C# language however was designed to keep business and enterprises needs in mind. C# language was
designed for businesses to build all kinds of software by using one single programming language.
C# provides functionality to support modern day software development. C# supports Web, Mobile, and
app development needs. Some of the modern-day programming language features C# supports are
generics, var types, auto initialization of types and collections, lambda expressions, dynamic
programming, asynchronous programming, tuples, pattern matching, advanced debugging and exception
handling, and more.
C# language syntaxes are influenced from C++, Java, Pascal and few other languages that are easy to
adopt. C# also avoids complexity and unstructured language features.
C# is fast and open source
C# is open source under the .NET Foundation, which is governed and run independently of Microsoft.
C# language specifications, compilers, and related tools are open source projects on GitHub. While C#
language feature design is led by Microsoft, the open source community is very active in the language
development and improvements.
C# is fast compare to several other high-level programming languages. C# 8 has many performance
improvements.
C# is cross platform
C# is cross platform programming language. You can build .NET applications that can be deployed on
Windows, Linux, and Mac platforms. C# apps can also be deployed in cloud and containers.
C# is safe and efficient
C# is a type safe language. C# does not allow type conversions that may lead to data loss or other
problems. C# allows developers to write safe code. C# also focuses on writing efficient code.
Here is a list of some of the key concepts in C# that helps write safe and efficient code.
 Unsafe type casting is not allowed.
 Nullable and non-nullable types are supported in C#.
 Declare a readonly struct to express that a type is immutable and enables the compiler to save
copies when using in parameters.
 Use a ref readonly return when the return value is a struct larger than IntPtr.Size and the storage
lifetime is greater than the method returning the value.
 When the size of a readonly struct is bigger than IntPtr.Size, you should pass it as an in parameter
for performance reasons.
 Never pass a struct as an in parameter unless it is declared with the readonly modifier because it
may negatively affect performance and could lead to an obscure behavior.
 Use a ref struct, or a readonly ref struct such as Span<T> or ReadOnlySpan<T> to work with
memory as a sequence of bytes.
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,
 Windows client applications
 Windows libraries and components
 Windows services
 Web applications
 Web services and Web API
 Native iOS and Android mobile apps
 Backend services
 Azure cloud applications and services
 Backend database using ML/Data tools
 Interoperability software such as Office, SharePoint, SQL Server and so on.
 Artificial Intelligence and Machine learning
 Block chains and distributed ledger technology including cryptocurrency
 Internet of Things (IoT) devices
 Gaming consoles and gaming systems
 Video games
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
1.0
1999-
2002
Modern, Object Oriented, Simple, Flexible, Typesafe, Managed, Garbage Collection,
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
6.0 2015
Compiler-as-a-service (Roslyn), Exception filters, Await in catch/finally blocks, Auto
property initializers, Dictionary initializer, Default values for getter-only properties,
Expression-bodied members. Null propagator, String interpolation, nameof operator
7.0 2017
Tuples, Out variables, Pattern matching, Deconstruction, Local functions, Digit
separators, Binary literals, Ref returns and locals, Generalized async return types,
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
7.2 2017
Reference semantics with value types, Non-trailing named arguments, Leading
underscores in numeric literals, private protected access modifier
7.3 2018
Accessing fixed fields without pinning, Reassigning ref local variables, Using initializers
on stackalloc arrays, Using fixed statements with any type that supports a pattern, Using
additional generic constraints
8.0 2019
Nullable reference types, Async streams, ranges and indices, default implementation of
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 0thposition. 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:
 Adding and inserting items to a collection
 Removing items from a collection
 Finding, sorting, searching items
 Replacing items
 Copy and clone collections and items
 Capacity and Count properties to find the capacity of the collection and number of items in the
collection
.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,
 Free Book: C# Programming for Beginners
 Object Oriented Programming Using C# .NET
 Free Book: Programming XML with C#
 Creating C# Class Library (DLL) Using Visual Studio .NET
 C# List Tutorial
 Learn C#: Working with Arrays in .NET
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;
intArray = new int[5];
C#
Copy
The following code snippet declares an array that can store 100 items starting from index 0 to 99.
int[] intArray;
intArray = new int[100];
C#
Copy
Arrays types in C#
In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can
define arrays of any type such as double, character, and string.
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.
double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];
C#
Copy
Initializing Array in C#
Once an array is declared, the next step is to initialize an array. The initialization process of an array
includes adding actual data to the array.
The following code snippet creates an array of 3 items and values of these items are added when the array
is initialized.
// Initialize a fixed array
int[] staticIntArray = new int[3] {1, 3, 5};
C#
Copy
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
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;
C#
Copy
The following code snippet declares a dynamic array with string values.
// Initialize a dynamic array items during declaration
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.
// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;
// Read array items one by one
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.
Accessing a C# array using a foreach Loop
The foreach control statement (loop) is used to iterate through the items of an array. For example, the
following code uses foreach loop to read all items of an array of strings.
// Initialize a dynamic array items during declaration
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"Dinesh Beniwal"
};
// Read array items using foreach loop
foreach(string str in strArray) {
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.
Single Dimension Arrays
Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store the
number of items of a predefined type. All items in a single dimension array are stored contiguously
starting from 0 to the size of the array -1.
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;
intArray = new int[3];
C#
Copy
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.
int[] staticIntArray = new int[3] {1, 3, 5};
C#
Copy
The following code declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
C#
Copy
You can even directly assign these values without using the new operator.
string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
C#
Copy
You can initialize a dynamic length array as follows.
string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
C#
Copy
Multi-Dimensional Arrays in C#
A multi-dimensional array, also known as a rectangular array is an array with more than one dimension.
The form of a multi-dimensional array is a matrix.
Declaring a multi-dimensional array
A multi-dimension array is declared as follows:
string[,] mutliDimStringArray;
C#
Copy
A multi-dimensional array can be fixed-sized or dynamic sized.
Initializing multi-dimensional arrays
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.
int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
C#
Copy
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 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
C#
Copy
You can also omit the new operator as we did in single dimension arrays. You can assign these values
directly without using the new operator. For example:
int[, ] numbers = {
{
1,
2
},
{
3,
4
},
{
5,
6
}
};
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.
int[, ] numbers = new int[3, 2];
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
Accessing multi-dimensional arrays
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.
Declaring Jagged 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.
int[][] intJaggedArray = new int[3][];
C#
Copy
The following code snippet declares a jagged array that has two items of an array.
string[][] stringJaggedArray = new string[2][];
C#
Copy
Initializing Jagged Arrays
Before a jagged array can be used, its items must be initialized. The following code snippet initializes a
jagged array; the first item with an array of integers that has two integers, second item with an array of
integers that has 4 integers, and the third item with an array of integers that has 6 integers.
// Initializing jagged arrays
intJaggedArray[0] = new int[2];
intJaggedArray[1] = new int[4];
intJaggedArray[2] = new int[6];
C#
Copy
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.
// Initializing jagged arrays
intJaggedArray[0] = new int[2] {
2,
12
};
intJaggedArray[1] = new int[4] {
4,
14,
24,
34
};
intJaggedArray[2] = new int[6] {
6,
16,
26,
36,
46,
56
};
C#
Copy
Accessing Jagged Arrays
We can access a jagged array's items individually in the following way:
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.
// Loop through all itesm of a jagged array
for (int i = 0; i < intJaggedArray3.Length; i++) {
System.Console.Write("Element({0}): ", i);
for (int j = 0; j < intJaggedArray3[i].Length; j++) {
System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" :
" ");
}
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.
Console.WriteLine("Single Dimension Array Sample");
// Single dim array
string[] strArray = new string[] {
"Mahesh Chand",
"Mike Gold",
"Raj Beniwal",
"Praveen Kumar",
"Dinesh Beniwal"
};
// Read array items using foreach loop
foreach(string str in strArray) {
Console.WriteLine(str);
}
Console.WriteLine("-----------------------------");
Console.WriteLine("Multi-Dimension Array Sample");
string[, ] string2DArray = new string[2, 2] {
{
"Rosy",
"Amy"
}, {
"Peter",
"Albert"
}
};
foreach(string str in string2DArray) {
Console.WriteLine(str);
}
Console.WriteLine("-----------------------------");
Console.WriteLine("Jagged Array Sample");
int[][] intJaggedArray3 = {
new int[] {
2,
12
},
new int[] {
14,
14,
24,
34
},
new int[] {
6,
16,
26,
36,
46,
56
}
};
// Loop through all itesm of a jagged array
for (int i = 0; i < intJaggedArray3.Length; i++) {
Console.Write($"Element({i}): ");
for (int j = 0; j < intJaggedArray3[i].Length; j++) {
Console.Write($"{intJaggedArray3[i][j]} ");
}
Console.WriteLine();
}
Console.WriteLine("-----------------------------");
C#
Copy
Listing 1
The output of Listing 1 looks like Figure 1.
Figure 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.
Array stringArray = Array.CreateInstance(typeof(String), 3);
stringArray.SetValue("Mahesh Chand", 0);
stringArray.SetValue("Raj Kumar", 1);
stringArray.SetValue("Neel Beniwal", 2);
C#
Copy
Note: Calling SetValue on an existing item of an array overrides the previous item value with the new
value.
The code snippet in Listing 2 creates a multi-dimensional array.
Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4);
for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++)
for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++)
for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++) {
intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k);
}
foreach(int ival in intArray3D) {
Console.WriteLine(ival);
}
C#
Copy
Listing 2
C# Array Properties
Table 1 describes Array class properties.
IsFixedSize Return a value indicating if an array has a fixed size or not.
IsReadOnly Returns a value indicating if an array is read-only or not.
LongLength Returns a 64-bit integer that represents a total number of items in all the dimensions of an array.
Length Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.
Rank Returns the number of dimensions of an array.
Table 1
The code snippet in Listing 3 creates an array and uses Array properties to display property values.
int[] intArray = new int[3] {
0,
1,
2
};
if (intArray.IsFixedSize) {
Console.WriteLine("Array is fixed size");
Console.WriteLine($"Size : {intArray.Length.ToString()}");
Console.WriteLine($"Rank : {intArray.Rank.ToString()}");
}
C#
Copy
Listing 3
The output of Listing looks like Figure 2.
Figure 2
Searching for an Item in an Array in C#
The BinarySearch static method of the Array class can be used to search for an item in an array. This
method uses the binary search algorithm to search for an item. The method takes at least two parameters.
The first parameter is the array in which you would like to search and a second parameter is an object
that is the item you are looking for. If an item is found in the array, the method returns the index of that
item (based on the first item as 0th item). Otherwise, the method returns a negative value.
Note
You must sort an array before searching. See the comments in this article.
Listing 4 uses the BinarySearch method to search an array for a string.
// Create an array and add 5 items to it
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0) Console.WriteLine($"Item was at {nameIndex.ToString()}th position");
else Console.WriteLine("Item not found");
C#
Copy
Listing 4
Sorting Items in an Array in C#
The Sort static method of the Array class can be used to sort array items. This method has many
overloaded forms. The simplest form takes as a parameter the array you want to sort. Listing 5 uses the
Sort method to sort array items. Using the Sort method, you can also sort a partial list of items.
// Create an array and add 5 items to it
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0) Console.WriteLine($"Item was at {nameIndex.ToString()}th position");
else Console.WriteLine("Item not found");
Console.WriteLine();
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
Console.WriteLine(str);
}
Console.WriteLine();
Console.WriteLine("Sorted Array");
Console.WriteLine("---------------------");
Array.Sort(stringArray);
foreach (string str in stringArray)
{
Console.WriteLine(str);
}
C#
Copy
Listing 5
The output of Listing 5 looks like Figure 3.
Figure 3
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
The new output looks like Figure 4.
Figure 4
Getting and Setting Values
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.
Array names = Array.CreateInstance(typeof(String), 2, 4);
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);
int items1 = names.GetLength(0);
int items2 = names.GetLength(1);
for (int i = 0; i < items1; i++)
for (int j = 0; j < items2; j++)
Console.WriteLine($"{i.ToString()},{j.ToString()}: {names.GetValue(i, j)}");
C#
Copy
Listing 6
The output of Listing 6 generates Figure 5.
Figure 5
Reverse an array items in C#
The Reverse static method of the Array class reverses the order of items in an array. Similar to the Sort
method, you can just pass an array as a parameter of the Reverse method.
Array stringArray = Array.CreateInstance(typeof(String), 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("---------------------");
foreach(string str in stringArray) {
Console.WriteLine(str);
}
Console.WriteLine();
Console.WriteLine("Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
// Array.Sort(stringArray, 2, 3);
foreach(string str in stringArray) {
Console.WriteLine(str);
}
Console.WriteLine();
Console.WriteLine("Double Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
// Array.Sort(stringArray, 2, 3);
foreach(string str in stringArray) {
Console.WriteLine(str);
}
C#
Copy
Listing 7
The output of Listing 7 generates Figure 6.
Figure 6
Clear an array items in C#
The Clear static method of the Array class removes all items of an array and sets its length to zero. This
method takes three parameters - first an array object, second starting index of the array and third is the
number of elements. The following code clears two elements from the array starting at index 1 (means
the second element of the array).
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.
Array stringArray = Array.CreateInstance(typeof(String), 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("---------------------");
foreach(string str in stringArray) {
Console.WriteLine(str);
}
Console.WriteLine();
Console.WriteLine("Clear Items");
Console.WriteLine("---------------------");
Array.Clear(stringArray, 1, 2);
foreach(string str in stringArray) {
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
Get the size of an array in C#
The GetLength method returns the number of items in an array. The GetLowerBound and
GetUppperBound methods return the lower and upper bounds of an array respectively. All these three
methods take at least a parameter, which is the index of the dimension of an array. The following code
snippet uses all three methods.
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.
// Creates and initializes a new Array of type Int32.
Array oddArray = Array.CreateInstance(Type.GetType("System.Int32"), 5);
oddArray.SetValue(1, 0);
oddArray.SetValue(3, 1);
oddArray.SetValue(5, 2);
oddArray.SetValue(7, 3);
oddArray.SetValue(9, 4);
// Creates and initializes a new Array of type Object.
Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5);
Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4);
int items1 = objArray.GetUpperBound(0);
for (int i = 0; i < items1; i++) Console.WriteLine(objArray.GetValue(i).ToString());
C#
Copy
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.
public static void Copy(Array, int, Array, int, int);
C#
Copy
Clone an Array in C#
Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements
of the Array, whether they are reference types or value types, but it does not copy the objects that the
references refer to. The references in the new Array point to the same objects that the references in the
original Array point to.
The following code snippet creates a cloned copy of an array of strings.
string[] clonedArray = (string[])stringArray.Clone();
C#
Copy
Summary
In this article, you learned the basics of arrays and how to use them C#. At the beginning of this article,
we discussed different types of arrays such as single dimension, multi-dimension, and jagged arrays.
After that, we discussed the Array class. At the end of this article, we saw how to work with arrays using
different methods and properties of the Array class.
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
System.String authorName = "Mahesh Chand";
// String made of an Integer
System.String age = "33";
// String made of a double
System.String numberString = "33.23";
C#
Copy
Here is the complete example that shows how to use stings in C# and .NET.
using System;
namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
// Define .NET Strings
// String of characters
System.String authorName = "Mahesh Chand";
// String made of an Integer
System.String age = "33";
// String made of a double
System.String numberString = "33.23";
// Write to Console.
Console.WriteLine("Name: {0}", authorName);
Console.WriteLine("Age: {0}", age);
Console.WriteLine("Number: {0}", numberString);
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.
3. What is different between String and System.String?
.NET defines all data types as a class. The System.String class represents a collection of Unicode
characters also known as a text. The System.String class also defines the properties and methods to work
with string data types.
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.
 Create a string using a constructor
 Create a string from a literal
 Create a string using concatenation
 Create a string using a property or a method
 Create a string using formatting
Create a string using its constructor
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.
char[] chars = { 'M', 'a', 'h', 'e', 's', 'h' };
string name = new string(chars);
Console.WriteLine(name);
C#
Copy
Create a string from a literal
This is the most common ways to instantiate a string.
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
Alternatively, we can assign the text value directly to the variable.
string firstName = "Mahesh";
C#
Copy
Here is a complete sample example of how to create strings using literals.
using System;
namespace CSharpStrings
{
class Program
{
static void Main(string[] args)
{
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
string numberString = "33.23";
Console.WriteLine("First Name: {0}", firstName);
Console.WriteLine("Last Name: {0}", lastName);
Console.WriteLine("Age: {0}", age);
Console.WriteLine("Number: {0}", numberString);
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 nowDateTime = "Date: " + DateTime.Now.ToString("D");
string firstName = "Mahesh";
string lastName = "Chand";
string age = "33";
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#.
6. Create a string using a property or a method
Some properties and methods of the String class returns a string object such as SubString method. The
following code snippet takes one sentence string and finds the age within that string. The code returns 33.
string authorInfo = "Mahesh Chand is 33 years old.";
int startPosition = sentence.IndexOf("is ") + 1;
string age = authorInfo.Substring(startPosition +2, 2 );
Console.WriteLine("Age: " + age);
C#
Copy
7. Create a string with Format
The String.Format method returns a string. The following code snippet creates a new string using the
Format method.
string name = "Mahesh Chand";
int age = 33;
string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString());
Console.WriteLine(authorInfo);
C#
Copy
Here is a detailed article on formatting string - Use of String.Format() To format strings in C#
8. Create a string using ToString Method
The ToString method returns a string. We can apply ToString on pretty much any data type that can be
converted to a string. The following code snippet converts an int data type to a string.
string name = "Mahesh Chand";
int age = 33;
string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString());
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.
string nameString = "Mahesh Chand";
for (int counter = 0; counter <= nameString.Length - 1; counter++)
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.
string nameString = "Mahesh Chand";
Console.WriteLine(nameString);
Console.WriteLine("Size of string {0}", nameString.Length);
C#
Copy
11. Get number of characters in a string
We can use the string.Length property to get the number of characters of a string but it will also count an
empty character. So, to find out the exact number of characters in a string, we need to remove the empty
character occurrences from a string.
The following code snippet uses the Replace method to remove empty characters and then displays the
non-empty characters of a string.
string name = "Mahesh Chand";
string name = "Mahesh Chand";
// Get size of string
Console.WriteLine("Size of string: {0}", name.Length );
// Remove all empty characters
string nameWithoutEmptyChar = name.Replace(" ", "");
// Size after empty characters are removed
Console.WriteLine("Size of non empty char string: {0}", nameWithoutEmptyChar.Length);
// Read and print all characters
for (int counter = 0; counter <= nameWithoutEmptyChar.Length - 1; counter++)
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.
string sentence = "Mahesh Chand is an author and founder of C# Corner";
char[] charArr = sentence.ToCharArray();
foreach (char ch in charArr)
{
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.
The following code snippet creates two empty strings.
string empStr = string.Empty;
string empStr2 = "";
C#
Copy
Both of the statements above generates the same output.
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.
string name = "Mahesh Chand";
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
Here is a complete example of using an empty string.
string empStr = string.Empty;
string empStr2 = "";
string name = "Mahesh Chand";
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.
The following code example shows how to use a null string.
string nullStr = null;
string empStr = string.Empty;
string name = "Mahesh Chand";
if ((name != nullStr) || (name != empStr))
{
Console.WriteLine(name + " is neither null nor empty");
}
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. }
Result from above code is show below:
In the above case, the program do not terminate unexpectedly. Instead, the program control passes from
the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch
block, executes the statements inside that catch and continues with the normal execution of the program
statements.
If a finally block is present, the code inside the finally block will get also be executed.
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. }
Catching all Exceptions
By providing a catch block without brackets or arguments, we can catch all exceptions occurred inside a
try block. Even we can use a catch block with an Exception type parameter to catch all exceptions
happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the
Exception class.
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. }
The following program handles all exception with Exception object.
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;
For example, the following statement throws an ArgumentException explicitly.
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.
This chapter covers the following:
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.
Simple "Hello World" C# Program
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
public class SimpleHelloWorld
{
//Entry point of the program
static void Main(string[] args)
{
//print Hello world"
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.
Compiling the Program
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:
csc /target:module "program name"
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
Classes and Objects
Classes are special kinds of templates from which you can create objects. Each object contains data and
methods to manipulate and access that data. The class defines the data and the functionality that each
object of that class can contain.
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 accessibility modifiers class identifier: baselist { body }
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.
Step-by-step Tutorial for Creating a Class
1. Open Visual Studio 2010 from start menu.
2. Go to "File" > "New" > "Project...", select "Console Application" in the right pane and provide the
name "oops" for the project.
3. Then in the Solution Explorer, you will notice some files that are automatically created as,
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
public int CustID;
public string Name;
public string Address;
//constuctor for initializing fields
customer()
{
CustID=1101;
Name="Tom";
Address="USA";
}
//method for displaying customer records (functionality)
public void displayData()
{
Console.WriteLine("Customer="+CustID);
Console.WriteLine("Name="+Name);
Console.WriteLine("Address="+Address);
}
// Code for entry point
}
}
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
{
// class members code
//Entry point
static void Main(string[] args)
{
// object instantiation
customer obj = new customer();
//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;
Image 1.1 Intellisense feature
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.
Multiple Class Declaration
Sometimes circumstances require multiple classes to be declared in a single namespace. So in that case
it is not mandatory to add a separate class to the solution, instead you can attach the new class into the
existing program.cs or another one as in the following;
using System;
namespace oops
{
class Program
{
public void MainFunction()
{
Console.WriteLine("Main class");
}
static void Main(string[] args)
{
//main class instance
Program obj = new Program();
obj.MainFunction();
//other class instace
demo dObj=new demo();
dObj.addition();
}
}
class demo
{
int x = 10;
int y = 20;
int z;
public void addition()
{
z = x + y;
Console.WriteLine("other class in Namespace");
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.
 Each partial type is preceded with the "partial" keyword.
 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
{
public partial class partialclassDemo
{
public void method1()
{
Console.WriteLine("method from part1 class");
}
}
}
C#
Copy
partialPart2.cs
using System;
namespace oops
{
public partial class partialclassDemo
{
public void method2()
{
Console.WriteLine("method from part2 class");
}
}
}
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
{
static void Main(string[] args)
{
//partial class instance
partialclassDemo obj = new partialclassDemo();
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 class staticDemo
{
//static fields
static int x = 10, y;
//static method
static void calcute()
{
y = x * x;
Console.WriteLine(y);
}
static void Main(string[] args)
{
//function calling directly
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
First create a class library based application as,
Then we are implementing a math class library that is responsible of calculating square root and the
addition of two numbers as:
using System;
namespace LibraryUtil
{
public class MathLib
{
public MathLib() { }
public void calculareSum(int x, int y)
{
int z = x + y;
Console.WriteLine(z);
}
public void calculareSqrt(double x)
{
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:tempLibraryUtilLibraryUtilbinDebug 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;
using LibraryUtil; // add library namespace
namespace oops
{
public class LibraryClass
{
static void Main()
{
//library class instance
MathLib obj = new MathLib();
//method populate
obj.calculareSum(2, 5);
obj.calculareSqrt(25);
}
}
}
C#
Copy
Finally run the application.
Constructor and Destructor
A constructor is a specialized function that is used to initialize fields. A constructor has the same name
as the class. Instance constructors are invoked with the new operator and can't be called in the same
manner as other member functions. There are some important rules pertaining to constructors as in the
following;
 Classes with no constructor have an implicit constructor called the default constructor, that is
parameterless. The default constructor assigns default values to fields.
 A public constructor allows an object to be created in the current assembly or referencing
assembly.
 Only the extern modifier is permitted on the constructor.
 A constructor returns void but does not have an explicitly declared return type.
 A constructor can have zero or more parameters.
 Classes can have multiple constructors in the form of default, parameter or both.
The following example shows one constructor for a customer class.
using System;
namespace oops
{
class customer
{
// Member Variables
public string Name;
//constuctor for initializing fields
public customer(string fname, string lname)
{
Name= fname +" "+ lname;
}
//method for displaying customer records
public void AppendData()
{
Console.WriteLine(Name);
}
//Entry point
static void Main(string[] args)
{
// object instantiation
customer obj = new customer("Barack", "Obama");
//Method calling
obj.AppendData();
}
}
}
C#
Copy
Note
The moment a new statement is executed, the default constructor is called.
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;
 Static constructors are parameterless.
 Static constructors can't be overloaded.
 There is no accessibility specified for Static constructors.
In the following example the customer class has a static constructor that initializes the static field and this
constructor is called when the class is referenced in the Main () at line 26 as in the following:
using System;
namespace oops
{
class customer
{
// Member Variables
static private int x;
//constuctor for static initializing fields
static customer()
{
x = 10;
}
//method for get static field
static public void getData()
{
Console.WriteLine(x);
}
//Entry point
static void Main(string[] args)
{
//static Method calling
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;
 Destructors are parameterless.
 A Destructor can't be overloaded.
 Destructors are not inherited.
 Destructors can cause performance and efficiency implications.
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;
//constuctor for initializing fields
customer()
{
Console.WriteLine("Fields inititalized");
x = 10;
}
//method for get field
public void getData()
{
y = x * x;
Console.WriteLine(y);
}
//method to release resource explicitly
public void Dispose()
{
Console.WriteLine("Fields cleaned");
x = 0;
y = 0;
}
//destructor
~customer()
{
Dispose();
}
//Entry point
static void Main(string[] args)
{
//instance created
customer obj = new customer();
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
{
public string name;
//overloaded functions
public void setName(string last)
{
name = last;
}
public void setName(string first, string last)
{
name = first + "" + last;
}
public void setName(string first, string middle, string last)
{
name = first + "" + middle + "" + last;
}
//Entry point
static void Main(string[] args)
{
funOverload obj = new funOverload();
obj.setName("barack");
obj.setName("barack "," obama ");
obj.setName("barack ","hussian","obama");
}
}
}
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
/// the outside inference
/// </summary>
// Encapsulation Begin
int x;
//class constructor
public Encapsulation(int iX)
{
this.x = iX;
}
//calculating the square
public void MySquare()
{
int Calc = x * x;
Console.WriteLine(Calc);
}
// End of Encapsulation
//Entry point
static void Main(string[] args)
{
//instance created
customer obj = new customer(20);
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.
The syntax of inheritance is as in the following;
Class derivedClass : baseClass, Iterface1, Interface2 { body }
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
public class Father
{
public void FatherMethod()
{
Console.WriteLine("this property belong to Father");
}
}
//Derived class
public class Child : Father
{
public void ChildMethod()
{
Console.WriteLine("this property belong to Child");
}
}
class Inheritance
{
//Entry point
static void Main(string[] args)
{
Father fObj = new Father();
fObj.FatherMethod();
//Here Child object can access both class methods
Child cObj = new Child();
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
Cross-language and multiple inheritance is not supported by .NET.
Accessibility
Accessibility sets the visibility of the member to outside assemblies or derived types. The following table
describes member accessibility;
Modifiers Outside Assembly Derived Class
private No No
public Yes Yes
protected No No
internal Yes ( this assembly only) Yes ( this assembly only)
internal protected Yes ( this assembly only) Yes
Constructor in Inheritance
Constructors in a base class are not inherited in a derived class. A derived class has a base portion and
derived portion. The base portion initializes the base portion, and the constructor of the derived class
initializes the derived portion.
The following is the syntax of a constructor in inheritance;
Accessibility modifier classname(parameterlist1) : base(parameterlist2) { body }
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
public class Father
{
//constructor
public Father()
{
Console.WriteLine("Father class constructor");
}
public void FatherMethod()
{
Console.WriteLine("this property belong to Father");
}
}
//Derived class
public class Child : Father
{
public Child()
: base()
{
Console.WriteLine("child class constructor");
}
public void ChildMethod()
{
Console.WriteLine("this property belong to Child");
}
}
class Inheritance
{
//Entry point
static void Main(string[] args)
{
//Here Child object can access both class methods
Child cObj = new Child();
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
public virtual void VirtualMethod()
{
Console.WriteLine("virtual method defined in the base class");
}
}
class myDerived : myBase
{
// redifing the implementation of base class method
public override void VirtualMethod()
{
Console.WriteLine("virtual method defined in the Derive class");
}
}
class virtualClass
{
static void Main(string[] args)
{
// 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
public virtual void VirtualMethod()
{
Console.WriteLine("virtual method defined in the base class");
}
}
class myDerived : myBase
{
// hiding the implementation of base class method
public new void VirtualMethod()
{
Console.WriteLine("virtual method defined in the Derive class");
//still access the base class method
base.VirtualMethod();
}
}
class virtualClass
{
static void Main(string[] args)
{
// 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
public abstract class Employess
{
//abstract method with no implementation
public abstract void displayData();
}
//derived class
public class test : Employess
{
//abstract class method implementation
public override void displayData()
{
Console.WriteLine("Abstract class method");
}
}
class abstractClass
{
static void Main(string[] args)
{
// 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
{
sealed class SealedClass
{
void myfunv();
}
public class test : SealedClass //wrong. will give compilation error
{
}
}
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;
 An Abstract class can contain some implementations but an interface can't.
 An Interface can only inherit other interfaces but abstract classes can inherit from other classes
and interfaces.
 An Abstract class can contain constructors and destructors but an interface can't.
 An Abstract class contains fields but interfaces don't.
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
public interface xyz
{
void methodA();
void methodB();
}
// interface method implementation
class test : xyz
{
public void methodA()
{
Console.WriteLine("methodA");
}
public void methodB()
{
Console.WriteLine("methodB");
}
}
class interfaceDemo
{
static void Main(string[] args)
{
test obj = new test();
obj.methodA();
obj.methodB();
}
}
}
C#
Copy
An interface can be inherited from other interfaces as in the following:
public interface xyz
{
void methodA();
void methodB();
}
public interface abc : xyz
{
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
{
public abstract class Employee
{
public virtual void LeaderName()
{
}
}
public class hrDepart : Employee
{
public override void LeaderName()
{
Console.WriteLine("Mr. jone");
}
}
public class itDepart : Employee
{
public override void LeaderName()
{
Console.WriteLine("Mr. Tom");
}
}
public class financeDepart : Employee
{
public override void LeaderName()
{
Console.WriteLine("Mr. Linus");
}
}
class PolymorphismDemo
{
static void Main(string[] args)
{
hrDepart obj1 = new hrDepart();
itDepart obj2 = new itDepart();
financeDepart obj3 = new financeDepart();
obj1.LeaderName();
obj2.LeaderName();
obj3.LeaderName();
Console.ReadKey();
}
}
}
C#
Copy
 .NET
 C#
 Object Oriented Programming
 OOP
Next Recommended ReadingInheritance in C#
OUR BOOKS








<
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. }
The expression in the above code can be any non-null expression.
Listing 1 demonstrates a typical switch statement. The switch expression is a random number between 1
and 9. Based on the value of the expression, a case block is executed. If the value of a switch expression
is doesn’t match with first three case values, the default block is executed.
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,
 A bool literal, either true or false.
 Any integral constant, such as an int, a long, or a byte.
 The name of a declared const variable.
 An enumeration constant.
 A char literal.
 A string literal.
The constant expression is evaluated as follows,
 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.
Listing 5 is an example of using a char constant in a switch statement.
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 case expression is true if any of the following is true:
 expr is an instance of the same type as type.
 expr is an instance of a type that derives from type. In other words, the result of expr can be upcast
to an instance of type.
 expr has a compile-time type that is a base class of type, and expr has a runtime type that is type
or is derived from type. The compile-time type of a variable is the variable's type as defined in its
type declaration. The runtime type of a variable is the type of the instance that is assigned to that
variable.
 expr is an instance of a type that implements the type interface.
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");
C-sharping.docx

Mais conteúdo relacionado

Semelhante a C-sharping.docx

C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#sudipv
 
Summer training PPT Manasv Singharia.pptx
Summer training PPT Manasv Singharia.pptxSummer training PPT Manasv Singharia.pptx
Summer training PPT Manasv Singharia.pptxshokeenk14
 
programming in c#.ppt
programming in c#.pptprogramming in c#.ppt
programming in c#.pptNalinaKumari2
 
Migrating From Cpp To C Sharp
Migrating From Cpp To C SharpMigrating From Cpp To C Sharp
Migrating From Cpp To C SharpGanesh Samarthyam
 
C# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkC# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkDr.Neeraj Kumar Pandey
 
A tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfA tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfParasJain570452
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.pptManiMala75
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.pptManiMala75
 
C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfComedyTechnology
 
over all view programming to computer
over all view programming to computer over all view programming to computer
over all view programming to computer muniryaseen
 
Chapter-1 C#.pptx
Chapter-1 C#.pptxChapter-1 C#.pptx
Chapter-1 C#.pptxfaarax4
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages mohamed drahem
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionAKR Education
 

Semelhante a C-sharping.docx (20)

Programming in c#
Programming in c#Programming in c#
Programming in c#
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#
 
Summer training PPT Manasv Singharia.pptx
Summer training PPT Manasv Singharia.pptxSummer training PPT Manasv Singharia.pptx
Summer training PPT Manasv Singharia.pptx
 
C# handout.docx
C# handout.docxC# handout.docx
C# handout.docx
 
Dot net
Dot netDot net
Dot net
 
programming in c#.ppt
programming in c#.pptprogramming in c#.ppt
programming in c#.ppt
 
Migrating From Cpp To C Sharp
Migrating From Cpp To C SharpMigrating From Cpp To C Sharp
Migrating From Cpp To C Sharp
 
C programming.pdf
C programming.pdfC programming.pdf
C programming.pdf
 
C# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkC# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net Framework
 
A tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfA tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdf
 
Presentation1
Presentation1Presentation1
Presentation1
 
1 puc programming using c++
1 puc programming using c++1 puc programming using c++
1 puc programming using c++
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
C#
C#C#
C#
 
C programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdfC programming language tutorial for beginers.pdf
C programming language tutorial for beginers.pdf
 
over all view programming to computer
over all view programming to computer over all view programming to computer
over all view programming to computer
 
Chapter-1 C#.pptx
Chapter-1 C#.pptxChapter-1 C#.pptx
Chapter-1 C#.pptx
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages
 
Unit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introductionUnit 1 of c++ part 1 basic introduction
Unit 1 of c++ part 1 basic introduction
 

Último

Jeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel ThrowingJeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel ThrowingJeremy Casson
 
Young⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort Servicesonnydelhi1992
 
GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607
GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607
GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607dollysharma2066
 
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...anilsa9823
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboardthephillipta
 
Editorial sephora annual report design project
Editorial sephora annual report design projectEditorial sephora annual report design project
Editorial sephora annual report design projecttbatkhuu1
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...akbard9823
 
Best Call girls in Lucknow - 9548086042 - with hotel room
Best Call girls in Lucknow - 9548086042 - with hotel roomBest Call girls in Lucknow - 9548086042 - with hotel room
Best Call girls in Lucknow - 9548086042 - with hotel roomdiscovermytutordmt
 
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...home
 
Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...
Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...
Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...anilsa9823
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKedwardsara83
 
Storyboard short: Ferrarius Tries to Sing
Storyboard short: Ferrarius Tries to SingStoryboard short: Ferrarius Tries to Sing
Storyboard short: Ferrarius Tries to SingLyneSun
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room servicediscovermytutordmt
 
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...anilsa9823
 
Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...
Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...
Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...anilsa9823
 
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...anilsa9823
 
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...akbard9823
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...anilsa9823
 
Bobbie goods coloring book 81 pag_240127_163802.pdf
Bobbie goods coloring book 81 pag_240127_163802.pdfBobbie goods coloring book 81 pag_240127_163802.pdf
Bobbie goods coloring book 81 pag_240127_163802.pdfMARIBEL442158
 
VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112
VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112
VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112Nitya salvi
 

Último (20)

Jeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel ThrowingJeremy Casson - Top Tips for Pottery Wheel Throwing
Jeremy Casson - Top Tips for Pottery Wheel Throwing
 
Young⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort ServiceYoung⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort Service
Young⚡Call Girls in Uttam Nagar Delhi >༒9667401043 Escort Service
 
GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607
GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607
GENUINE EscoRtS,Call Girls IN South Delhi Locanto TM''| +91-8377087607
 
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
Lucknow 💋 Russian Call Girls Lucknow | Whatsapp No 8923113531 VIP Escorts Ser...
 
Alex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson StoryboardAlex and Chloe by Daniel Johnson Storyboard
Alex and Chloe by Daniel Johnson Storyboard
 
Editorial sephora annual report design project
Editorial sephora annual report design projectEditorial sephora annual report design project
Editorial sephora annual report design project
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
 
Best Call girls in Lucknow - 9548086042 - with hotel room
Best Call girls in Lucknow - 9548086042 - with hotel roomBest Call girls in Lucknow - 9548086042 - with hotel room
Best Call girls in Lucknow - 9548086042 - with hotel room
 
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
Authentic # 00971556872006 # Hot Call Girls Service in Dubai By International...
 
Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...
Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...
Lucknow 💋 (Call Girls) in Mahanagar | Service-oriented sexy call girls 892311...
 
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAKRAK Call Girls Service # 971559085003 # Call Girl Service In RAK
RAK Call Girls Service # 971559085003 # Call Girl Service In RAK
 
Storyboard short: Ferrarius Tries to Sing
Storyboard short: Ferrarius Tries to SingStoryboard short: Ferrarius Tries to Sing
Storyboard short: Ferrarius Tries to Sing
 
Call girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room serviceCall girls in Kanpur - 9761072362 with room service
Call girls in Kanpur - 9761072362 with room service
 
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
Lucknow 💋 Call Girls Service Lucknow ₹7.5k Pick Up & Drop With Cash Payment 8...
 
Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...
Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...
Lucknow 💋 Russian Call Girls Sushant Golf City - 450+ Call Girl Cash Payment ...
 
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
 
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
 
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
Lucknow 💋 Call Girl in Lucknow Phone No 8923113531 Elite Escort Service Avail...
 
Bobbie goods coloring book 81 pag_240127_163802.pdf
Bobbie goods coloring book 81 pag_240127_163802.pdfBobbie goods coloring book 81 pag_240127_163802.pdf
Bobbie goods coloring book 81 pag_240127_163802.pdf
 
VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112
VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112
VIP Ramnagar Call Girls, Ramnagar escorts Girls 📞 8617697112
 

C-sharping.docx

  • 1. C# is a strongly typed object-oriented programming language. C# is open source, simple, modern, flexible, and versatile. In this article, let us learn what C# is, what C# can do, and how C# is different from C++ and other programming languages. A programming language on computer science is a language that is used to write software programs. C# is a programming language developed and launched by Microsoft in 2001. C# is a simple, modern, and object-oriented language that provides modern day developers flexibility and features to build software that will not only work today but will be applicable for years in the future. Key characteristics of C# language include: 1. Modern and easy 2. Fast and open source 3. Cross platform 4. Safe 5. Versatile 6. Evolving C# is modern and easy C# is a simple, modern, and an object-oriented programming language. The purpose of C# was to develop a programming language that is not only easy to learn but also supports modern day functionality for all kind of software development. If you look at the history of programming languages and their features, each programming language was designed for a specific purpose to solve a specific need at that time. C# language however was designed to keep business and enterprises needs in mind. C# language was designed for businesses to build all kinds of software by using one single programming language. C# provides functionality to support modern day software development. C# supports Web, Mobile, and app development needs. Some of the modern-day programming language features C# supports are generics, var types, auto initialization of types and collections, lambda expressions, dynamic programming, asynchronous programming, tuples, pattern matching, advanced debugging and exception handling, and more. C# language syntaxes are influenced from C++, Java, Pascal and few other languages that are easy to adopt. C# also avoids complexity and unstructured language features. C# is fast and open source C# is open source under the .NET Foundation, which is governed and run independently of Microsoft. C# language specifications, compilers, and related tools are open source projects on GitHub. While C# language feature design is led by Microsoft, the open source community is very active in the language development and improvements. C# is fast compare to several other high-level programming languages. C# 8 has many performance improvements. C# is cross platform C# is cross platform programming language. You can build .NET applications that can be deployed on Windows, Linux, and Mac platforms. C# apps can also be deployed in cloud and containers.
  • 2. C# is safe and efficient C# is a type safe language. C# does not allow type conversions that may lead to data loss or other problems. C# allows developers to write safe code. C# also focuses on writing efficient code. Here is a list of some of the key concepts in C# that helps write safe and efficient code.  Unsafe type casting is not allowed.  Nullable and non-nullable types are supported in C#.  Declare a readonly struct to express that a type is immutable and enables the compiler to save copies when using in parameters.  Use a ref readonly return when the return value is a struct larger than IntPtr.Size and the storage lifetime is greater than the method returning the value.  When the size of a readonly struct is bigger than IntPtr.Size, you should pass it as an in parameter for performance reasons.  Never pass a struct as an in parameter unless it is declared with the readonly modifier because it may negatively affect performance and could lead to an obscure behavior.  Use a ref struct, or a readonly ref struct such as Span<T> or ReadOnlySpan<T> to work with memory as a sequence of bytes. 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,  Windows client applications  Windows libraries and components  Windows services  Web applications  Web services and Web API  Native iOS and Android mobile apps  Backend services  Azure cloud applications and services  Backend database using ML/Data tools  Interoperability software such as Office, SharePoint, SQL Server and so on.  Artificial Intelligence and Machine learning  Block chains and distributed ledger technology including cryptocurrency  Internet of Things (IoT) devices  Gaming consoles and gaming systems  Video games 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.
  • 3. The following table summarizes the C# versions with year and features. Version Year Features 1.0 1999- 2002 Modern, Object Oriented, Simple, Flexible, Typesafe, Managed, Garbage Collection, 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 6.0 2015 Compiler-as-a-service (Roslyn), Exception filters, Await in catch/finally blocks, Auto property initializers, Dictionary initializer, Default values for getter-only properties, Expression-bodied members. Null propagator, String interpolation, nameof operator 7.0 2017 Tuples, Out variables, Pattern matching, Deconstruction, Local functions, Digit separators, Binary literals, Ref returns and locals, Generalized async return types, 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 7.2 2017 Reference semantics with value types, Non-trailing named arguments, Leading underscores in numeric literals, private protected access modifier 7.3 2018 Accessing fixed fields without pinning, Reassigning ref local variables, Using initializers on stackalloc arrays, Using fixed statements with any type that supports a pattern, Using additional generic constraints 8.0 2019 Nullable reference types, Async streams, ranges and indices, default implementation of 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. {
  • 4. 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 0thposition. 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.
  • 5. 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:  Adding and inserting items to a collection  Removing items from a collection  Finding, sorting, searching items  Replacing items  Copy and clone collections and items  Capacity and Count properties to find the capacity of the collection and number of items in the collection .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,  Free Book: C# Programming for Beginners  Object Oriented Programming Using C# .NET  Free Book: Programming XML with C#  Creating C# Class Library (DLL) Using Visual Studio .NET  C# List Tutorial  Learn C#: Working with Arrays in .NET C# Books C# Corner provides several C# language programming books. Here are a few:
  • 6. 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;
  • 7. 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; intArray = new int[5]; C# Copy The following code snippet declares an array that can store 100 items starting from index 0 to 99. int[] intArray; intArray = new int[100]; C# Copy Arrays types in C# In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string. 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. double[] doubleArray = new double[5]; char[] charArray = new char[5]; bool[] boolArray = new bool[2]; string[] stringArray = new string[10]; C# Copy Initializing Array in C# Once an array is declared, the next step is to initialize an array. The initialization process of an array includes adding actual data to the array. The following code snippet creates an array of 3 items and values of these items are added when the array is initialized. // Initialize a fixed array int[] staticIntArray = new int[3] {1, 3, 5}; C# Copy Alternative, we can also add array items one at a time as listed in the following code snippet.
  • 8. // Initialize a fixed array one item at a time int[] staticIntArray = new int[3]; staticIntArray[0] = 1; staticIntArray[1] = 3; staticIntArray[2] = 5; C# Copy The following code snippet declares a dynamic array with string values. // Initialize a dynamic array items during declaration 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. // Initialize a fixed array one item at a time int[] staticIntArray = new int[3]; staticIntArray[0] = 1; staticIntArray[1] = 3; staticIntArray[2] = 5; // Read array items one by one 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. Accessing a C# array using a foreach Loop The foreach control statement (loop) is used to iterate through the items of an array. For example, the following code uses foreach loop to read all items of an array of strings. // Initialize a dynamic array items during declaration string[] strArray = new string[] {
  • 9. "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" }; // Read array items using foreach loop foreach(string str in strArray) { 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. Single Dimension Arrays Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store the number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1. 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; intArray = new int[3]; C# Copy 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. int[] staticIntArray = new int[3] {1, 3, 5};
  • 10. C# Copy The following code declares and initializes an array of 5 string items. string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" }; C# Copy You can even directly assign these values without using the new operator. string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" }; C# Copy You can initialize a dynamic length array as follows. string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" }; C# Copy Multi-Dimensional Arrays in C# A multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix. Declaring a multi-dimensional array A multi-dimension array is declared as follows: string[,] mutliDimStringArray; C# Copy A multi-dimensional array can be fixed-sized or dynamic sized. Initializing multi-dimensional arrays 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. int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; string[,] names = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } }; C# Copy 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 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } }; C# Copy
  • 11. You can also omit the new operator as we did in single dimension arrays. You can assign these values directly without using the new operator. For example: int[, ] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 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. int[, ] numbers = new int[3, 2]; numbers[0, 0] = 1;
  • 12. numbers[1, 0] = 2; numbers[2, 0] = 3; numbers[0, 1] = 4; numbers[1, 1] = 5; numbers[2, 1] = 6; C# Copy Accessing multi-dimensional arrays 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. Declaring Jagged 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. int[][] intJaggedArray = new int[3][]; C# Copy The following code snippet declares a jagged array that has two items of an array. string[][] stringJaggedArray = new string[2][]; C# Copy Initializing Jagged Arrays
  • 13. Before a jagged array can be used, its items must be initialized. The following code snippet initializes a jagged array; the first item with an array of integers that has two integers, second item with an array of integers that has 4 integers, and the third item with an array of integers that has 6 integers. // Initializing jagged arrays intJaggedArray[0] = new int[2]; intJaggedArray[1] = new int[4]; intJaggedArray[2] = new int[6]; C# Copy 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. // Initializing jagged arrays intJaggedArray[0] = new int[2] { 2, 12 }; intJaggedArray[1] = new int[4] { 4, 14, 24, 34 }; intJaggedArray[2] = new int[6] { 6, 16, 26, 36, 46, 56 }; C# Copy Accessing Jagged Arrays
  • 14. We can access a jagged array's items individually in the following way: 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. // Loop through all itesm of a jagged array for (int i = 0; i < intJaggedArray3.Length; i++) { System.Console.Write("Element({0}): ", i); for (int j = 0; j < intJaggedArray3[i].Length; j++) { System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " "); } 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. Console.WriteLine("Single Dimension Array Sample"); // Single dim array string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar",
  • 15. "Dinesh Beniwal" }; // Read array items using foreach loop foreach(string str in strArray) { Console.WriteLine(str); } Console.WriteLine("-----------------------------"); Console.WriteLine("Multi-Dimension Array Sample"); string[, ] string2DArray = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } }; foreach(string str in string2DArray) { Console.WriteLine(str); } Console.WriteLine("-----------------------------"); Console.WriteLine("Jagged Array Sample"); int[][] intJaggedArray3 = { new int[] { 2, 12 }, new int[] { 14, 14,
  • 16. 24, 34 }, new int[] { 6, 16, 26, 36, 46, 56 } }; // Loop through all itesm of a jagged array for (int i = 0; i < intJaggedArray3.Length; i++) { Console.Write($"Element({i}): "); for (int j = 0; j < intJaggedArray3[i].Length; j++) { Console.Write($"{intJaggedArray3[i][j]} "); } Console.WriteLine(); } Console.WriteLine("-----------------------------"); C# Copy Listing 1 The output of Listing 1 looks like Figure 1.
  • 17. Figure 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. Array stringArray = Array.CreateInstance(typeof(String), 3); stringArray.SetValue("Mahesh Chand", 0); stringArray.SetValue("Raj Kumar", 1); stringArray.SetValue("Neel Beniwal", 2); C# Copy Note: Calling SetValue on an existing item of an array overrides the previous item value with the new value. The code snippet in Listing 2 creates a multi-dimensional array. Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4); for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++) for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++)
  • 18. for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++) { intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k); } foreach(int ival in intArray3D) { Console.WriteLine(ival); } C# Copy Listing 2 C# Array Properties Table 1 describes Array class properties. IsFixedSize Return a value indicating if an array has a fixed size or not. IsReadOnly Returns a value indicating if an array is read-only or not. LongLength Returns a 64-bit integer that represents a total number of items in all the dimensions of an array. Length Returns a 32-bit integer that represents the total number of items in all the dimensions of an array. Rank Returns the number of dimensions of an array. Table 1 The code snippet in Listing 3 creates an array and uses Array properties to display property values. int[] intArray = new int[3] { 0, 1, 2 }; if (intArray.IsFixedSize) { Console.WriteLine("Array is fixed size"); Console.WriteLine($"Size : {intArray.Length.ToString()}"); Console.WriteLine($"Rank : {intArray.Rank.ToString()}"); } C# Copy Listing 3 The output of Listing looks like Figure 2.
  • 19. Figure 2 Searching for an Item in an Array in C# The BinarySearch static method of the Array class can be used to search for an item in an array. This method uses the binary search algorithm to search for an item. The method takes at least two parameters. The first parameter is the array in which you would like to search and a second parameter is an object that is the item you are looking for. If an item is found in the array, the method returns the index of that item (based on the first item as 0th item). Otherwise, the method returns a negative value. Note You must sort an array before searching. See the comments in this article. Listing 4 uses the BinarySearch method to search an array for a string. // Create an array and add 5 items to it Array stringArray = Array.CreateInstance(typeof(String), 5); stringArray.SetValue("Mahesh", 0); stringArray.SetValue("Raj", 1); stringArray.SetValue("Neel", 2); stringArray.SetValue("Beniwal", 3); stringArray.SetValue("Chand", 4); // Find an item object name = "Neel"; int nameIndex = Array.BinarySearch(stringArray, name); if (nameIndex >= 0) Console.WriteLine($"Item was at {nameIndex.ToString()}th position"); else Console.WriteLine("Item not found"); C# Copy Listing 4 Sorting Items in an Array in C# The Sort static method of the Array class can be used to sort array items. This method has many overloaded forms. The simplest form takes as a parameter the array you want to sort. Listing 5 uses the Sort method to sort array items. Using the Sort method, you can also sort a partial list of items. // Create an array and add 5 items to it
  • 20. Array stringArray = Array.CreateInstance(typeof(String), 5); stringArray.SetValue("Mahesh", 0); stringArray.SetValue("Raj", 1); stringArray.SetValue("Neel", 2); stringArray.SetValue("Beniwal", 3); stringArray.SetValue("Chand", 4); // Find an item object name = "Neel"; int nameIndex = Array.BinarySearch(stringArray, name); if (nameIndex >= 0) Console.WriteLine($"Item was at {nameIndex.ToString()}th position"); else Console.WriteLine("Item not found"); Console.WriteLine(); Console.WriteLine("Original Array"); Console.WriteLine("---------------------"); foreach (string str in stringArray) { Console.WriteLine(str); } Console.WriteLine(); Console.WriteLine("Sorted Array"); Console.WriteLine("---------------------"); Array.Sort(stringArray); foreach (string str in stringArray) { Console.WriteLine(str); } C# Copy Listing 5 The output of Listing 5 looks like Figure 3.
  • 21. Figure 3 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 The new output looks like Figure 4. Figure 4 Getting and Setting Values 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.
  • 22. In the end, I find a number of items in both dimensions and use GetValue method to read values and display on the console. Array names = Array.CreateInstance(typeof(String), 2, 4); 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); int items1 = names.GetLength(0); int items2 = names.GetLength(1); for (int i = 0; i < items1; i++) for (int j = 0; j < items2; j++) Console.WriteLine($"{i.ToString()},{j.ToString()}: {names.GetValue(i, j)}"); C# Copy Listing 6 The output of Listing 6 generates Figure 5. Figure 5 Reverse an array items in C# The Reverse static method of the Array class reverses the order of items in an array. Similar to the Sort method, you can just pass an array as a parameter of the Reverse method. Array stringArray = Array.CreateInstance(typeof(String), 5); stringArray.SetValue("Mahesh", 0);
  • 23. stringArray.SetValue("Raj", 1); stringArray.SetValue("Neel", 2); stringArray.SetValue("Beniwal", 3); stringArray.SetValue("Chand", 4); Console.WriteLine("Original Array"); Console.WriteLine("---------------------"); foreach(string str in stringArray) { Console.WriteLine(str); } Console.WriteLine(); Console.WriteLine("Reversed Array"); Console.WriteLine("---------------------"); Array.Reverse(stringArray); // Array.Sort(stringArray, 2, 3); foreach(string str in stringArray) { Console.WriteLine(str); } Console.WriteLine(); Console.WriteLine("Double Reversed Array"); Console.WriteLine("---------------------"); Array.Reverse(stringArray); // Array.Sort(stringArray, 2, 3); foreach(string str in stringArray) { Console.WriteLine(str); } C# Copy Listing 7 The output of Listing 7 generates Figure 6.
  • 24. Figure 6 Clear an array items in C# The Clear static method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters - first an array object, second starting index of the array and third is the number of elements. The following code clears two elements from the array starting at index 1 (means the second element of the array). 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. Array stringArray = Array.CreateInstance(typeof(String), 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("---------------------"); foreach(string str in stringArray) { Console.WriteLine(str);
  • 25. } Console.WriteLine(); Console.WriteLine("Clear Items"); Console.WriteLine("---------------------"); Array.Clear(stringArray, 1, 2); foreach(string str in stringArray) { 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 Get the size of an array in C# The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The following code snippet uses all three methods. Console.WriteLine(stringArray.GetLength(0).ToString()); Console.WriteLine(stringArray.GetLowerBound(0).ToString()); Console.WriteLine(stringArray.GetUpperBound(0).ToString()); C#
  • 26. 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. // Creates and initializes a new Array of type Int32. Array oddArray = Array.CreateInstance(Type.GetType("System.Int32"), 5); oddArray.SetValue(1, 0); oddArray.SetValue(3, 1); oddArray.SetValue(5, 2); oddArray.SetValue(7, 3); oddArray.SetValue(9, 4); // Creates and initializes a new Array of type Object. Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5); Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4); int items1 = objArray.GetUpperBound(0); for (int i = 0; i < items1; i++) Console.WriteLine(objArray.GetValue(i).ToString()); C# Copy 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. public static void Copy(Array, int, Array, int, int); C# Copy Clone an Array in C# Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to. The following code snippet creates a cloned copy of an array of strings. string[] clonedArray = (string[])stringArray.Clone(); C# Copy Summary
  • 27. In this article, you learned the basics of arrays and how to use them C#. At the beginning of this article, we discussed different types of arrays such as single dimension, multi-dimension, and jagged arrays. After that, we discussed the Array class. At the end of this article, we saw how to work with arrays using different methods and properties of the Array class. 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 System.String authorName = "Mahesh Chand"; // String made of an Integer System.String age = "33"; // String made of a double System.String numberString = "33.23"; C# Copy Here is the complete example that shows how to use stings in C# and .NET. using System; namespace CSharpStrings { class Program { static void Main(string[] args) { // Define .NET Strings
  • 28. // String of characters System.String authorName = "Mahesh Chand"; // String made of an Integer System.String age = "33"; // String made of a double System.String numberString = "33.23"; // Write to Console. Console.WriteLine("Name: {0}", authorName); Console.WriteLine("Age: {0}", age); Console.WriteLine("Number: {0}", numberString); 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. 3. What is different between String and System.String? .NET defines all data types as a class. The System.String class represents a collection of Unicode characters also known as a text. The System.String class also defines the properties and methods to work with string data types. 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
  • 29. There are several ways to construct strings in C# and .NET.  Create a string using a constructor  Create a string from a literal  Create a string using concatenation  Create a string using a property or a method  Create a string using formatting Create a string using its constructor 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. char[] chars = { 'M', 'a', 'h', 'e', 's', 'h' }; string name = new string(chars); Console.WriteLine(name); C# Copy Create a string from a literal This is the most common ways to instantiate a string. 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 Alternatively, we can assign the text value directly to the variable. string firstName = "Mahesh"; C# Copy Here is a complete sample example of how to create strings using literals. using System; namespace CSharpStrings { class Program { static void Main(string[] args)
  • 30. { string firstName = "Mahesh"; string lastName = "Chand"; string age = "33"; string numberString = "33.23"; Console.WriteLine("First Name: {0}", firstName); Console.WriteLine("Last Name: {0}", lastName); Console.WriteLine("Age: {0}", age); Console.WriteLine("Number: {0}", numberString); 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 nowDateTime = "Date: " + DateTime.Now.ToString("D"); string firstName = "Mahesh"; string lastName = "Chand"; string age = "33"; 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#. 6. Create a string using a property or a method
  • 31. Some properties and methods of the String class returns a string object such as SubString method. The following code snippet takes one sentence string and finds the age within that string. The code returns 33. string authorInfo = "Mahesh Chand is 33 years old."; int startPosition = sentence.IndexOf("is ") + 1; string age = authorInfo.Substring(startPosition +2, 2 ); Console.WriteLine("Age: " + age); C# Copy 7. Create a string with Format The String.Format method returns a string. The following code snippet creates a new string using the Format method. string name = "Mahesh Chand"; int age = 33; string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString()); Console.WriteLine(authorInfo); C# Copy Here is a detailed article on formatting string - Use of String.Format() To format strings in C# 8. Create a string using ToString Method The ToString method returns a string. We can apply ToString on pretty much any data type that can be converted to a string. The following code snippet converts an int data type to a string. string name = "Mahesh Chand"; int age = 33; string authorInfo = string.Format("{0} is {1} years old.", name, age.ToString()); 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. string nameString = "Mahesh Chand"; for (int counter = 0; counter <= nameString.Length - 1; counter++) Console.WriteLine(nameString[counter]); C#
  • 32. 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. string nameString = "Mahesh Chand"; Console.WriteLine(nameString); Console.WriteLine("Size of string {0}", nameString.Length); C# Copy 11. Get number of characters in a string We can use the string.Length property to get the number of characters of a string but it will also count an empty character. So, to find out the exact number of characters in a string, we need to remove the empty character occurrences from a string. The following code snippet uses the Replace method to remove empty characters and then displays the non-empty characters of a string. string name = "Mahesh Chand"; string name = "Mahesh Chand"; // Get size of string Console.WriteLine("Size of string: {0}", name.Length ); // Remove all empty characters string nameWithoutEmptyChar = name.Replace(" ", ""); // Size after empty characters are removed Console.WriteLine("Size of non empty char string: {0}", nameWithoutEmptyChar.Length); // Read and print all characters for (int counter = 0; counter <= nameWithoutEmptyChar.Length - 1; counter++) Console.WriteLine(nameWithoutEmptyChar[counter]); C# Copy 12. Convert String to Char Array
  • 33. ToCharArray method converts a string to an array of Unicode characters. The following code snippet converts a string to char array and displays them. string sentence = "Mahesh Chand is an author and founder of C# Corner"; char[] charArr = sentence.ToCharArray(); foreach (char ch in charArr) { 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. The following code snippet creates two empty strings. string empStr = string.Empty; string empStr2 = ""; C# Copy Both of the statements above generates the same output. 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. string name = "Mahesh Chand"; 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);
  • 34. } C# Copy Here is a complete example of using an empty string. string empStr = string.Empty; string empStr2 = ""; string name = "Mahesh Chand"; 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. The following code example shows how to use a null string. string nullStr = null; string empStr = string.Empty; string name = "Mahesh Chand"; if ((name != nullStr) || (name != empStr)) { Console.WriteLine(name + " is neither null nor empty"); } C# Copy
  • 35. 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
  • 36. 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. } Result from above code is show below:
  • 37. In the above case, the program do not terminate unexpectedly. Instead, the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements. If a finally block is present, the code inside the finally block will get also be executed. 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
  • 38. 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. }
  • 39. 26. Console.WriteLine($"Result is {div}"); 27. } 28. } Catching all Exceptions By providing a catch block without brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class. 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. } The following program handles all exception with Exception object. 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. }
  • 40. 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; For example, the following statement throws an ArgumentException explicitly. 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. {
  • 41. 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
  • 42. 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. This chapter covers the following: 1. OOP's overview 2. Classes and Objects 3. Constructor and Destructor 4. Function Overloading 5. Encapsulation 6. Inheritance 7. Interface 8. Polymorphism
  • 43. 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. Simple "Hello World" C# Program 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 public class SimpleHelloWorld { //Entry point of the program static void Main(string[] args) { //print Hello world" Console.WriteLine("Hello World!"); }
  • 44. } } 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. Compiling the Program 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: csc /target:module "program name" 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 Classes and Objects Classes are special kinds of templates from which you can create objects. Each object contains data and methods to manipulate and access that data. The class defines the data and the functionality that each object of that class can contain. 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 accessibility modifiers class identifier: baselist { body } 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;
  • 45. 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. Step-by-step Tutorial for Creating a Class 1. Open Visual Studio 2010 from start menu. 2. Go to "File" > "New" > "Project...", select "Console Application" in the right pane and provide the name "oops" for the project. 3. Then in the Solution Explorer, you will notice some files that are automatically created as, 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;
  • 46. 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.
  • 47. 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 public int CustID; public string Name; public string Address; //constuctor for initializing fields customer() { CustID=1101; Name="Tom"; Address="USA"; } //method for displaying customer records (functionality) public void displayData() { Console.WriteLine("Customer="+CustID); Console.WriteLine("Name="+Name); Console.WriteLine("Address="+Address); } // Code for entry point }
  • 48. } 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 { // class members code //Entry point static void Main(string[] args) { // object instantiation customer obj = new customer(); //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;
  • 49. Image 1.1 Intellisense feature 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. Multiple Class Declaration Sometimes circumstances require multiple classes to be declared in a single namespace. So in that case it is not mandatory to add a separate class to the solution, instead you can attach the new class into the existing program.cs or another one as in the following; using System; namespace oops { class Program { public void MainFunction() { Console.WriteLine("Main class"); } static void Main(string[] args) { //main class instance Program obj = new Program();
  • 50. obj.MainFunction(); //other class instace demo dObj=new demo(); dObj.addition(); } } class demo { int x = 10; int y = 20; int z; public void addition() { z = x + y; Console.WriteLine("other class in Namespace"); 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;
  • 51.  A partial type must have the same accessibility.  Each partial type is preceded with the "partial" keyword.  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 { public partial class partialclassDemo { public void method1() { Console.WriteLine("method from part1 class"); } } } C# Copy partialPart2.cs using System; namespace oops { public partial class partialclassDemo { public void method2() { Console.WriteLine("method from part2 class"); }
  • 52. } } 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 { static void Main(string[] args) { //partial class instance partialclassDemo obj = new partialclassDemo(); 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 class staticDemo {
  • 53. //static fields static int x = 10, y; //static method static void calcute() { y = x * x; Console.WriteLine(y); } static void Main(string[] args) { //function calling directly 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 First create a class library based application as,
  • 54. Then we are implementing a math class library that is responsible of calculating square root and the addition of two numbers as: using System; namespace LibraryUtil { public class MathLib { public MathLib() { } public void calculareSum(int x, int y) { int z = x + y; Console.WriteLine(z); } public void calculareSqrt(double x) { double z = Math.Sqrt(x); Console.WriteLine(z);
  • 55. } } } 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:tempLibraryUtilLibraryUtilbinDebug 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; using LibraryUtil; // add library namespace namespace oops { public class LibraryClass { static void Main() { //library class instance MathLib obj = new MathLib();
  • 56. //method populate obj.calculareSum(2, 5); obj.calculareSqrt(25); } } } C# Copy Finally run the application. Constructor and Destructor A constructor is a specialized function that is used to initialize fields. A constructor has the same name as the class. Instance constructors are invoked with the new operator and can't be called in the same manner as other member functions. There are some important rules pertaining to constructors as in the following;  Classes with no constructor have an implicit constructor called the default constructor, that is parameterless. The default constructor assigns default values to fields.  A public constructor allows an object to be created in the current assembly or referencing assembly.  Only the extern modifier is permitted on the constructor.  A constructor returns void but does not have an explicitly declared return type.  A constructor can have zero or more parameters.  Classes can have multiple constructors in the form of default, parameter or both. The following example shows one constructor for a customer class. using System; namespace oops { class customer { // Member Variables public string Name; //constuctor for initializing fields
  • 57. public customer(string fname, string lname) { Name= fname +" "+ lname; } //method for displaying customer records public void AppendData() { Console.WriteLine(Name); } //Entry point static void Main(string[] args) { // object instantiation customer obj = new customer("Barack", "Obama"); //Method calling obj.AppendData(); } } } C# Copy Note The moment a new statement is executed, the default constructor is called. 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;  Static constructors are parameterless.  Static constructors can't be overloaded.  There is no accessibility specified for Static constructors.
  • 58. In the following example the customer class has a static constructor that initializes the static field and this constructor is called when the class is referenced in the Main () at line 26 as in the following: using System; namespace oops { class customer { // Member Variables static private int x; //constuctor for static initializing fields static customer() { x = 10; } //method for get static field static public void getData() { Console.WriteLine(x); } //Entry point static void Main(string[] args) { //static Method calling customer.getData(); } } } C# Copy Destructors
  • 59. 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;  Destructors are parameterless.  A Destructor can't be overloaded.  Destructors are not inherited.  Destructors can cause performance and efficiency implications. 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; //constuctor for initializing fields customer() { Console.WriteLine("Fields inititalized"); x = 10; } //method for get field public void getData() { y = x * x; Console.WriteLine(y); } //method to release resource explicitly
  • 60. public void Dispose() { Console.WriteLine("Fields cleaned"); x = 0; y = 0; } //destructor ~customer() { Dispose(); } //Entry point static void Main(string[] args) { //instance created customer obj = new customer(); 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;
  • 61. namespace oops { class funOverload { public string name; //overloaded functions public void setName(string last) { name = last; } public void setName(string first, string last) { name = first + "" + last; } public void setName(string first, string middle, string last) { name = first + "" + middle + "" + last; } //Entry point static void Main(string[] args) { funOverload obj = new funOverload(); obj.setName("barack"); obj.setName("barack "," obama "); obj.setName("barack ","hussian","obama");
  • 62. } } } 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 /// the outside inference /// </summary> // Encapsulation Begin int x; //class constructor public Encapsulation(int iX)
  • 63. { this.x = iX; } //calculating the square public void MySquare() { int Calc = x * x; Console.WriteLine(Calc); } // End of Encapsulation //Entry point static void Main(string[] args) { //instance created customer obj = new customer(20); 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.
  • 64. 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. The syntax of inheritance is as in the following; Class derivedClass : baseClass, Iterface1, Interface2 { body } 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 public class Father { public void FatherMethod() { Console.WriteLine("this property belong to Father"); } }
  • 65. //Derived class public class Child : Father { public void ChildMethod() { Console.WriteLine("this property belong to Child"); } } class Inheritance { //Entry point static void Main(string[] args) { Father fObj = new Father(); fObj.FatherMethod(); //Here Child object can access both class methods Child cObj = new Child(); 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
  • 66. Cross-language and multiple inheritance is not supported by .NET. Accessibility Accessibility sets the visibility of the member to outside assemblies or derived types. The following table describes member accessibility; Modifiers Outside Assembly Derived Class private No No public Yes Yes protected No No internal Yes ( this assembly only) Yes ( this assembly only) internal protected Yes ( this assembly only) Yes Constructor in Inheritance Constructors in a base class are not inherited in a derived class. A derived class has a base portion and derived portion. The base portion initializes the base portion, and the constructor of the derived class initializes the derived portion. The following is the syntax of a constructor in inheritance; Accessibility modifier classname(parameterlist1) : base(parameterlist2) { body } 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 public class Father { //constructor public Father() { Console.WriteLine("Father class constructor"); } public void FatherMethod()
  • 67. { Console.WriteLine("this property belong to Father"); } } //Derived class public class Child : Father { public Child() : base() { Console.WriteLine("child class constructor"); } public void ChildMethod() { Console.WriteLine("this property belong to Child"); } } class Inheritance { //Entry point static void Main(string[] args) { //Here Child object can access both class methods Child cObj = new Child(); cObj.FatherMethod(); cObj.ChildMethod(); Console.ReadKey(); } }
  • 68. } 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 public virtual void VirtualMethod() { Console.WriteLine("virtual method defined in the base class"); } } class myDerived : myBase { // redifing the implementation of base class method public override void VirtualMethod() { Console.WriteLine("virtual method defined in the Derive class"); } } class virtualClass {
  • 69. static void Main(string[] args) { // 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 public virtual void VirtualMethod() { Console.WriteLine("virtual method defined in the base class"); } } class myDerived : myBase {
  • 70. // hiding the implementation of base class method public new void VirtualMethod() { Console.WriteLine("virtual method defined in the Derive class"); //still access the base class method base.VirtualMethod(); } } class virtualClass { static void Main(string[] args) { // 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 {
  • 71. //abstract class public abstract class Employess { //abstract method with no implementation public abstract void displayData(); } //derived class public class test : Employess { //abstract class method implementation public override void displayData() { Console.WriteLine("Abstract class method"); } } class abstractClass { static void Main(string[] args) { // 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.
  • 72. 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 { sealed class SealedClass { void myfunv(); } public class test : SealedClass //wrong. will give compilation error { } } 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;  An Abstract class can contain some implementations but an interface can't.  An Interface can only inherit other interfaces but abstract classes can inherit from other classes and interfaces.  An Abstract class can contain constructors and destructors but an interface can't.  An Abstract class contains fields but interfaces don't. 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 public interface xyz { void methodA();
  • 73. void methodB(); } // interface method implementation class test : xyz { public void methodA() { Console.WriteLine("methodA"); } public void methodB() { Console.WriteLine("methodB"); } } class interfaceDemo { static void Main(string[] args) { test obj = new test(); obj.methodA(); obj.methodB(); } } } C# Copy An interface can be inherited from other interfaces as in the following: public interface xyz { void methodA();
  • 74. void methodB(); } public interface abc : xyz { 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 { public abstract class Employee { public virtual void LeaderName() { } } public class hrDepart : Employee { public override void LeaderName() { Console.WriteLine("Mr. jone"); } }
  • 75. public class itDepart : Employee { public override void LeaderName() { Console.WriteLine("Mr. Tom"); } } public class financeDepart : Employee { public override void LeaderName() { Console.WriteLine("Mr. Linus"); } } class PolymorphismDemo { static void Main(string[] args) { hrDepart obj1 = new hrDepart(); itDepart obj2 = new itDepart(); financeDepart obj3 = new financeDepart(); obj1.LeaderName(); obj2.LeaderName(); obj3.LeaderName(); Console.ReadKey(); }
  • 76. } } C# Copy  .NET  C#  Object Oriented Programming  OOP Next Recommended ReadingInheritance in C# OUR BOOKS    
  • 78. 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. } The expression in the above code can be any non-null expression. Listing 1 demonstrates a typical switch statement. The switch expression is a random number between 1 and 9. Based on the value of the expression, a case block is executed. If the value of a switch expression is doesn’t match with first three case values, the default block is executed. 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.");
  • 79. 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.
  • 80. 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,  A bool literal, either true or false.  Any integral constant, such as an int, a long, or a byte.  The name of a declared const variable.  An enumeration constant.  A char literal.  A string literal. The constant expression is evaluated as follows,
  • 81.  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. Listing 5 is an example of using a char constant in a switch statement. 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 case expression is true if any of the following is true:  expr is an instance of the same type as type.
  • 82.  expr is an instance of a type that derives from type. In other words, the result of expr can be upcast to an instance of type.  expr has a compile-time type that is a base class of type, and expr has a runtime type that is type or is derived from type. The compile-time type of a variable is the variable's type as defined in its type declaration. The runtime type of a variable is the type of the instance that is assigned to that variable.  expr is an instance of a type that implements the type interface. 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");