[go: up one dir, main page]

0% found this document useful (0 votes)
118 views55 pages

C# Tutorial - The Fundamentals You Need To Master C# - Edureka

The Fundamentals you Need to Master C#

Uploaded by

Abhishek Dabar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views55 pages

C# Tutorial - The Fundamentals You Need To Master C# - Edureka

The Fundamentals you Need to Master C#

Uploaded by

Abhishek Dabar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

C# Tutorial: The Fundamentals you Need to Master C#


Last updated on Nov 26,2019 508 Views

Ravi Kiran
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning...

C# is all-purpose and the robust programming language developed by Microsoft Corporation in the year 2000 as a deadly
competitor to Java. It is most popular and a dominating programming language when it comes to both web development as well
as desktop application development.

In this C# Tutorial, we will learn the following concepts.

C# Basics
Object-Oriented Programming
Advanced C# Concepts
Interview Questions based on C#

C# Basics
Introduction to C# Programming Language
Features of C# Programming Language
Installation
C# Program Structure
Datatypes
Variables
Operators
Loops
Conditional
Strings
Arrays
Collections
List
Hash Set
Sorted Set
Stack
Queue
Linked List
Dictionary
Sorted Dictionary
Sorted List
Structure
Functions

Introduction to C# Programming Language

Back in the early 90s, Java was the leading programming language for web development, desktop application development and
many other elds. Microsoft wanted to come up with a competitor with many advanced features that can leave Java far behind.

https://www.edureka.co/blog/c-sharp-tutorial/ 1/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

It was in the year 2000, Anders Hejlsberg and his Microsoft team in came up with the idea of C# popularly called as C-Sharp.
This initiative was approved by the International Standards Organisation (ISO) and the European Computer Manufacturers
Association (ECMA). and nally, The C# enters the world of software development. 

Features of C# Programming Language

Object-Oriented Programming Language

Object-Oriented Programming approach is what makes C# sharp to be the most programmer-friendly and easy to develop
and maintain programming language.

Type-Safe Language

The meaning of Type-Safe is that the compiler will be given access only to the memory location that has the permission to
execute. This feature improves the code safety to an exponential level.

Interoperability

The feature of Interoperability makes C# capable enough to do everything that is native to C++ in a more e cient way that
can outperform C++ itself.

Rich Library

C# provides access to multiple numbers of in-built libraries that provide preprogrammed functionalities to decrease the
time spent in the development process.

Scalable and Updateable

C# was designed to be superior amongst the other programming languages. Hence, it is always open to updates and it
keeps itself highly scalable with its features.

Component Oriented

The developers at Microsoft used the component-based approach to develope C#. This is the most predominant
development methodology to keep C# highly scalable and updated.

Structured Language
https://www.edureka.co/blog/c-sharp-tutorial/ 2/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

The Structured Programming approach is preferred during the software development life-cycle as it becomes easy to
develop compile and deploy the software compared to the procedure-oriented programming approach.

Fast

C# Programming happens to be faster in compilation and execution compared to C++ and other programming languages.

Installation 

It is proven that Microsoft Visual Studio is the best in class Editor for C# Programming. We will install and Set up Microsoft
Visual Studio for executing our C# Programs by following the steps mentioned below:

Step 1: Download Microsoft Visual Studio

Google for the latest version of Visual Studio and download the installer le into your local system and then run the installer
le as an administrator.

Step 2: Select the .NET Desktop Development Package 

Once you run the Installer, the Visual Studio Editor will be successfully downloaded into your local system, Later a dialogue box
will be displayed on your desktop screen asking foe a particular package you need in your system. Here, you need to select the
.NET Desktop Development package.

https://www.edureka.co/blog/c-sharp-tutorial/ 3/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Step 3: Set C# Environment

Once your packages for .NET Development are downloaded, then another dialogue box will be displayed on your screen asking
for the development environment you are looking for. Here, you need to select the environment for C#.

Step 4: Create your First Project

Once the environment is set, you are all good to go. Start your Visual Studio and select create new project option in the
displayed dialogue box.

You will be redirected to the next dialogue box and there you need to select Class library as .NET Standard as shown below.

https://www.edureka.co/blog/c-sharp-tutorial/ 4/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

In the next dialogue box, you will be asked to Con gure your project. Con gure it and you are now in the Editor. Write your rst
program and run it. The output will be successfully displayed on the Command Prompt.

1 using System;
2 class Edureka
3 {
4 static void Main(string[] args)
5 {
6 Console.WriteLine("Welcome to Edureka!, Happy Learning..!");
7 }
8 }

//Output:

https://www.edureka.co/blog/c-sharp-tutorial/ 5/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Let us execute our rst C# Program.

C# Program Structure

Now that we have executed our rst C# Program, let us understand its structure in detail. A simple C# program has the following
parts.

1 using System;
2 namespace ConsoleApplication1
3 {
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 Console.WriteLine("Welcome to Edureka!, Happy Learning..!");
9 }
10 }
11 }

//Output:

Welcome to Edureka!, Happy Learning..!

class: class can be generally de ned as a keyword that is used to de ne a class in the C#  Program.
Edureka: It is the name of the Class. Class is often considered as a blueprint that stores the members and methods related
to the class.
Main:  Basically is the primary method of the whole C# Program, It acts as the gateway for the control to enter the
program. It gets executed before any other method of the program is executed.
void: This segment of the code is designated to the return type of the method. It can be any Datatype other than void.
Void means the method does not have any data getting returned from it.
static: This is a keyword which says the data members declared are static and a dedicated memory is been allocated to the
members declared.
String[] args: It resembles the command line arguments that we use in our program. While we execute our program, we
basically pass some arguments, which will be accepted by the program because of this statement.
System.Console.WriteLine(“Welcome to Edureka!, Happy Learning..!”); Here, System is the namespace. The console is
that the  category  outlined in System namespace. The WriteLine() is that the  static  technique  of Console  category  that  is
employed to write down the text on the console.

Now, let us learn the Datatypes available in C#.

Datatypes

The datatypes in C# are divided into three categories are described below.

https://www.edureka.co/blog/c-sharp-tutorial/ 6/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Value Datatypes

The Value Datatypes are located in the System.ValueType Library and are always ready to be directly accessed and variables
can be directly assigned to a particular value. The Value Datatypes are further classi ed into two types as shown below:

Prede ned Datatypes


User-de ned Datatypes

Prede ned Datatypes:  These are the ones which we normally use in our day to day programming. These Datatypes are
prede ned by the language developers and are kept ready to use for the programmers.

Example:

int, oat, char, short double, etc

User-De ned Datatypes: There are situations where we might need to store di erent values from Datatypes into one single
variable. In these cases, the Prede ned Datatypes aren’t just enough. User-De ned Datatypes are like customizable datatypes
for the user.

Example: Structure, Enum

Datatype Range of the Memory Allocated Memory Size


signed char -128 to 127   1 Byte
unsigned char  0 to 127  1 Byte
char -128 to 127   1 Byte
signed short -32,768 to 32,767   2 Bytes
unsigned short  0 to 65,535  2 Bytes
short -32,768 to 32,767   2 Bytes
signed int -2,147,483,648 to -2,147,483,647   4 Bytes
unsigned int 0 to 4,294,967,295   4 Bytes
int -2,147,483,648 to -2,147,483,647   4 Bytes
signed long  -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807   8 Bytes
 unsigned long 0 to 18,446,744,073,709,551,615   8 Bytes
 long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807   8 Bytes
  oat 1.5 * 10-45 – 3.4 * 1038, (7-digit precision)   4 Bytes
 double 5.0 * 10-324 – 1.7 * 10308, (15-digit precision)   8 Bytes
 decimal -7.9 * 10-28 – 7.9 * 1028, (28-digit precision)   16 Bytes

Pointer Datatype

Pointer Type is a simple datatype. Its functionality is completely similar to the Pointers in C. They are designed to store the
address of another pointer.

1 float* ptr; 

https://www.edureka.co/blog/c-sharp-tutorial/ 7/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Reference Datatypes

The name is self-explanatory. The Reference Datatypes actually do not store the variables, instead, they store the reference
value to that particular variable. In other words, they store the address of the actual variable.

The Reference Variables are classi ed into three di erent types as mentioned below:

Object type

The Object Datatype is available in the System.Object Class. The object  types can be  assigned to the  values of  the
other types, reference types, prede ned, user-de ned types. But, before assignment values, it requires type conversion.

1 object abc;
2 abc = 50; //this is called boxing

Dynamic Type 

Dynamic Type variables are designed to store almost all types of values. It is called as Dynamic Type because the type-
checking of values takes place in run-time

1 dynamic x=10;

String Type

The String Type is available in System.String class. The String Type is designed to store string literals. The String Literals are
stored in two forms in two forms

quoted
@quoted.

1 String S = "Edureka";

The @quoted string literal looks like

1 @"Edureka";

Now let us understand the variables.

Variables

Variables are the names allotted for the memory location that store certain data given by the user and that data is easily
accessible by using the variable name. There are ve types of variables available in C#

Type Example
Null Null data
Boolean True and False
Integer Int, Char, Byte, Short, Long
Float Float and Double
Decimal Decimal

Example:

1 int a, b;
2 double x;
3 float p;
4 char abc;

Rules to be followed to declare variables in C#

A variable can include alphabets, digits and underscores.


A variable name can only start with an alphabet or an underscore only.
Variables can not start with a digit or special character.
White spaces are not allowed in between the variable name.
Reserved keywords are restricted from being used as variable names.

https://www.edureka.co/blog/c-sharp-tutorial/ 8/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Operators

An Operator can be de ned as a special symbol that explains the computer to perform a particular Mathematical are a Logical
Operation upon a set of variables. C# includes a variety of Operators which are mentioned as below.

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators

Arithmetic Operators

Operator Example Description


+ A+B Adds two Operands
– A–B Substracts two Operands
* A*B Multiples two Operands
/ A/B Divides two Operands
% A%B The remainder of Two Operands
++ A++ Increment Operation
— A– Decrement Operation

Relational Operators

Operator Example Description


== A == B True, if both operands are equal, Else False
!= A != B True, if both operands are not equal, Else False
> A>B True, if A is Greater, Else False
< A<B True, if B is Greater, Else False
>= A >= B True, if A is Greater or equal, Else False
<= A <= B True, id B is Greater equal, Else False

Logical Operators

Operator Example Description


&& A && B True, if both operands are true, Else False
|| A || B True, if one of the operands is true, Else False
! A!B Reverses the logical state of the operand

Bitwise Operators

A B A&B A|B A^B


1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Operator Example Description


Binary One’s Complement Operator is unary and has the e ect of
~ (~A)
‘ ipping’ bits.
Binary Left Shift Operator. The left operands value is moved left
<< A<<2
by the number of bits speci ed by the right operand.

>> A>>2
Binary Right Shift Operator. The left operands value is moved
right by the number of bits speci ed by the right operand.

https://www.edureka.co/blog/c-sharp-tutorial/ 9/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Assignment Operators

Operator Example Description


= A = B+C A=B+C, B+C is assigned to A
+= A += B A=A+B, A+B is assigned to A
-= A -= B A=A-B, A-B is assigned to A
*= A -= B A=A*B, A*B is assigned to A
/= A /= B A=A/B, A/B is assigned to A
%= A %= B A=A%B, A%B is assigned to A
<<= A <<= 2 Left Shift and Assignment Operator
>>= A >>= 2 Right Shift and Assignment Operator
&= A &= 2 Bitwise and Assignment Operator
^= A ^= 2 Bitwise Exclusive and Assignment Operator
|= A != 2 Bitwise Inclusive and Assignment Operator

Loops

A loop statement is used for executing a block of statements repeatedly until a particular condition is satis ed. The C# Language
consists of the following Loop Statements.

For Loop
While Loop
Do While Loop

For Loop

The for loop is used to execute a particular code segment for multiple times until the given condition is satis ed. 

Syntax

1 for(initialization; condition; increment/decrement)


2 {
3 //code segment
4 }

FlowChart:

Example: 

https://www.edureka.co/blog/c-sharp-tutorial/ 10/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 public class ForExample
3 {
4 public static void Main(string[] args)
5 {
6 for (int i = 1; i<= 5; i++)
7 {
8 Console.WriteLine(i);
9 }
10 }
11 }

//Output:

1
2
3
4
5

While Loop

The While loop is used to execute a code segment for multiple numbers of times until a speci c condition is satis ed.

Syntax

1 while(condition)
2 {
3 //code to be executed
4 }

FlowChart:

Example:

1 using System;
2
3 namespace Loops
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 int x = 5;
10 while (x<= 10)
11 {
12 Console.WriteLine("The value of a: {0}", x);
13 x++;
14 }
15 Console.ReadLine();
16 }
17 }
18 }

//Output:

The value of a: 5 
The value of a: 6
The value of a: 7

https://www.edureka.co/blog/c-sharp-tutorial/ 11/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

The value of a: 8
The value of a: 9
The value of a: 10

Do While Loop

Do while loop is completely similar to While Loop but the only di erence is that the condition is placed at the end of the loop.
Hence, the loop is executed at least for once.

Syntax

1 do
2 {
3 //code to be executed
4 }while(condition);

FlowChart:

Example:

1 using System;
2 namespace Edureka
3 {
4 class DoWhileLoop
5 {
6 public static void Main(string[] args)
7 {
8 int i = 1, n = 5, product;
9 do
10 {
11 product = n * i;
12 Console.WriteLine("{0} * {1} = {2}", n, i, product);
13 i++;
14 } while (i<= 10);
15 }
16 }
17 }

//Output:

5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Conditional

Conditional statements are used to execute statement or group of statements based on some condition. If the condition is
true then C# statements are executed otherwise the next statement will be executed.
https://www.edureka.co/blog/c-sharp-tutorial/ 12/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Di erent types of Conditional Statements in C++ Language are as follows:

1. If statement
2. If-Else statement
3. Nested If-else statement
4. If-Else If ladder
5. Switch statement

If statement

The single  if  statement in C# language is used to execute the code if a condition is true. It is also called one-way selection
statement.

Syntax

1 if (boolean-expression)
2 {
3 // statements executed if boolean-expression is true
4 }

FlowChart:

Example:

1 using System;
2 namespace Conditional
3 {
4 class IfStatement
5 {
6 public static void Main(string[] args)
7 {
8 int number = 2;
9 if (number<5)
10 {
11 Console.WriteLine("{0} is less than 5", number);
12 }
13 Console.WriteLine("This statement is always executed.");
14 }
15 }
16 }

//Output:

2 is less than 5
This statement is always executed.


If-Else statement

https://www.edureka.co/blog/c-sharp-tutorial/ 13/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

The if-else statement in C language is used to execute the code if the condition is true or false. It is also called two-way selection
statement.

Syntax

1 if (boolean-expression)
2 {
3 // statements executed if boolean-expression is true
4 }
5 else
6 {
7 // statements executed if boolean-expression is false
8 }

FlowChart:

Example:

1 using System;
2 namespace Conditional
3 {
4 class IfElseStatement
5 {
6 public static void Main(string[] args)
7 {
8 int number = 12;
9 if (number<5)
10 {
11 Console.WriteLine("{0} is less than 5", number);
12 }
13 else
14 {
15 Console.WriteLine("{0} is greater than or equal to 5", number);
16 }
17 Console.WriteLine("This statement is always executed.");
18 }
19 }
20 }

//Output:

12 is greater than or equal to 5


This statement is always executed.

Nested If-else statement

The nested  if-else  statement is used when a program requires more than one test expression. It is also called a multi-way
selection statement. When a series of the decision are involved in a statement, we use if-else statement in nested form.

Syntax 

https://www.edureka.co/blog/c-sharp-tutorial/ 14/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 if (boolean-expression)
2 {
3 if (nested-expression-1)
4 {
5 // code to be executed
6 }
7 else
8 {
9 // code to be executed
10 }
11 }
12 else
13 {
14 if (nested-expression-2)
15 {
16 // code to be executed
17 }
18 else
19 {
20 // code to be executed
21 }
22 }

FlowChart:

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 15/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2
3 namespace Conditional
4 {
5 class Nested
6 {
7 public static void Main(string[] args)
8 {
9 int first = 7, second = -23, third = 13;
10 if (first > second)
11 {
12 if (first<third)
13 {
14 Console.WriteLine("{0} is the largest", first);
15 }
16 else
17 {
18 Console.WriteLine("{0} is the largest", third);
19 }
20 }
21 else
22 {
23 if (second<third)
24 {
25 Console.WriteLine("{0} is the largest", second);
26 }
27 else
28 {
29 Console.WriteLine("{0} is the largest", third);
30 }
31 }
32 }
33 }
34 }

//Output:

13 is the largest

Else-if Ladder

The if-else-if statement is used to execute one code from multiple conditions. It is also called multipath decision statement. It is a
chain of if..else statements in which each if statement is associated with else if statement and last would be an else statement.

Syntax

1 if(condition1)
2 {
3 // code to be executed if condition1 is true
4 }
5 else if(condition2)
6 {
7 // code to be executed if condition2 is true
8 }
9 else if(condition3)
10 {
11 // code to be executed if condition3 is true
12 }
13 ...
14 else
15 {
16 // code to be executed if all the conditions are false
17 }

FlowChart:

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 16/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2
3 class Edureka
4 {
5 public static void Main(String[] args)
6 {
7 int i = 20;
8 if (i == 10)
9 Console.WriteLine("i is 10");
10 else if (i == 15)
11 Console.WriteLine("i is 15");
12 else if (i == 20)
13 Console.WriteLine("i is 20");
14 else
15 Console.WriteLine("i is not present");
16 }
17 }

//Output:

i is 20

Switch statement

Switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases. A switch statement contains
one or more case labels which are tested against the switch expression. When the expression match to a case then the
associated statements with that case would be executed.

Syntax

1 switch (variable/expression)
2 {
3 case value1:
4 // Statements executed if expression(or variable) = value1
5 break;
6 case value2:
7 // Statements executed if expression(or variable) = value1
8 break;
9 ... ... ...
10 ... ... ...
11 default:
12 // Statements executed if no case matches
13 }

FlowChart:

https://www.edureka.co/blog/c-sharp-tutorial/ 17/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Example:

1 using System;
2
3 namespace Conditional
4 {
5 class SwitchCase
6 {
7 public static void Main(string[] args)
8 {
9 char ch;
10 Console.WriteLine("Enter an alphabet");
11 ch = Convert.ToChar(Console.ReadLine());
12 switch (Char.ToLower(ch))
13 {
14 case 'a':
15 Console.WriteLine("Vowel");
16 break;
17 case 'e':
18 Console.WriteLine("Vowel");
19 break;
20 case 'i':
21 Console.WriteLine("Vowel");
22 break;
23 case 'o':
24 Console.WriteLine("Vowel");
25 break;
26 case 'u':
27 Console.WriteLine("Vowel");
28 break;
29 default:
30 Console.WriteLine("Not a vowel");
31 break;
32 }
33 }
34 }
35 }

//Output:

Enter an alphabet
e
Vowel


Strings

https://www.edureka.co/blog/c-sharp-tutorial/ 18/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

String Datatype is a member of System.String Class. It is capable to store character type of data. We can perform various
operations on Stings such as concatenation, comparison, getting substring, search, trim, replacement and many more.

The analogy of String and string

In C# String and string are equivalent. The word string is a keyword and acts as the System.String class. We can use either of
the versions to declare strings.

Syntax:

1 string s1 = "Edureka";//creating string using string keyword


2 String s2 = "Happy Learning";//creating string using String class

Example:

1 using System;
2 public class StringExample
3 {
4 public static void Main(string[] args)
5 {
6 string s1 = "Edureka";
7 char[] ch = { 'C', 's', 'h', 'a', 'r', 'p',' ','T','u','t','o','r','i','a','l' };
8 string s2 = new string(ch);
9 Console.WriteLine(s1);
10 Console.WriteLine(s2);
11 }
12 }

//Output:

Edureka
Csharp Tutorial

String Methods in C# 

Method Description
Clone() Used to return a reference to this instance of String.
Compare(String, String) Used to compare two speci ed String objects.
Concat(String, String) Concatenate two speci ed instances of String.
Contains(String) Return a value indicating a speci ed sub-string
Copy(String) Used to create a new instance of String with the same value
CopyTo(Int, Char[], Int, Int) Copies characters from a speci ed position
Equals(String, String) Determines that two String objects have the same value.
Format(String, Object) Replace one or more format items in a speci ed string
IndexOf(String) Reports the zero-based index of the rst occurrence
Insert(Int32, String) Returns a new string in which a string is inserted at an index.
IsInterned(String)  Indicates that this string is in Unicode normalization form C.
IsNullOrEmpty(String) Indicates that the speci ed string is null or an empty string.
IsNullOrWhiteSpace(String) Used to indicate whether a speci ed string is null, empty,
Join(String, String[]) Used to concatenate all the elements of a string array
LastIndexOf(Char)   Reports the zero-based index position of the last character
LastIndexOfAny(Char[]) Reports the zero-based index position of the last character
Remove(Int32) Returns a new string in which all the characters
Replace(String, String) Returns a new string in which all occurrences of a string
Split(Char[]) It is used to split a string into substrings
StartsWith(String) It is used to check whether the beginning of this string
Substring(Int32) It is used to retrieve a substring from this instance.
ToCharArray()  Copies the characters in this instance to a Unicode array.
ToString() It is used to return the instance of String.
Trim() Trims the string


Arrays

https://www.edureka.co/blog/c-sharp-tutorial/ 19/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Similar to other programming languages, C# does have arrays. Arrays are the simple data structures that are designed to store
the same datatype of elements in a contiguous memory location.

C# supports the following Array types.

Single Dimensional Array


Multidimensional Array
Jagged Array

Single Dimensional Array

Single Dimensional Array stores elements in the form of one single row.

Syntax

1 int[] arr = new int[5];//creating array

Example:

1 using System;
2 public class ArrayExample
3 {
4 public static void Main(string[] args)
5 {
6 int[] arr = new int[5]; arr[0] = 10;
7 arr[1] = 20;
8 arr[2] = 30;
9 arr[3] = 40;
10 arr[4] = 50;
11 for (int i = 0; i < arr.Length; i++)
12 {
13 Console.WriteLine(arr[i]);
14 }
15 }
16 }

//Output:

10
20
30
40
50

Multidimensional Array

Multidimensional Array stores elements in the form of multiple dimensions like a matrix and a cube etc.

Syntax

1 int val = a[2,3];

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 20/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2
3 namespace ArrayApplication
4 {
5 class MyArray
6 {
7 static void Main(string[] args)
8 {
9 int[,] a = new int[5, 2] { { 0, 0 }, { 1, 2 }, { 2, 4 }, { 3, 6 }, { 4, 8 } };
10 int i, j;
11 for (i = 0; i < 5; i++)
12 {
13 for (j = 0; j < 2; j++)
14 {
15 Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]);
16 }
17 }
18 Console.ReadKey();
19 }
20 }
21 }

//Output:

a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
a[3,0] = 3
a[3,1] = 6
a[4,0] = 4
a[4,1] = 8

Jagged Array

Jagged Array is simply an array of arrays.

Example:

1 using System;
2
3 namespace ArrayApplication
4 {
5 class MyArray
6 {
7 static void Main(string[] args)
8 {
9 int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
10 new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
11 int i, j;
12 for (i = 0; i < 5; i++)
13 {
14 for (j = 0; j < 2; j++)
15 {
16 Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
17 }
18 }
19 Console.ReadKey();
20 }
21 }
22 }

//Output:

https://www.edureka.co/blog/c-sharp-tutorial/ 21/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8

Collections

Collection can be simply considered as a group of objects collected together so as to apply some functions upon the collected
data. The operations that once ca possibly perform on a collection are,

store object
update object
delete object
retrieve object
search object, and
sort object

Types of Collections

There are three di erent possibilities to work with collections. The three namespaces are mentioned below:

System.Collections.Generic classes
System.Collections classes
System.Collections.Concurrent classes

The System.Collections.Generic Class has the following varieties of classes:

List
Stack
Queue
LinkedList
HashSet
SortedSet
Dictionary
SortedDictionary
SortedList

The System.Collections classes are considered as legacy classes. they include the following classes.

ArrayList
Stack
Queue
Hashtable

The System.Collections.Concurrent classes namespace provides classes for thread-safe operations. Now multiple threads will
not create a problem for accessing the collection items. the classes available in this are,

BlockingCollection
ConcurrentBag
ConcurrentStack
ConcurrentQueue
ConcurrentDictionary<tkey, tvalue=””></tkey,>
Partitioner
Partitioner
OrderablePartitioner

https://www.edureka.co/blog/c-sharp-tutorial/ 22/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

List

The list is considered as a data structure available in System.Collection.Generics namespace. It can store and fetch elements.
The list is capable to store duplicate elements.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 var names = new List<string>();
9 names.Add("Sandhya");
10 names.Add("Arun");
11 names.Add("Prashanth");
12 names.Add("Kiran");
13 foreach (var name in names)
14 {
15 Console.WriteLine(name);
16 }
17 }
18 }

//Output:

Sandhya
Arun
Prashanth
Kiran

Hash Set

C# HashSet  category  is often  accustomed  store,  take away  or  read  components. It  doesn’t  store
duplicate  components.  it’s  urged  to use HashSet  category  if  you’ve got  to store  solely  distinctive  components.  it’s  found in
System.Collections.Generic namespace.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 var names = new HashSet<string>();
9 names.Add("Sunil");
10 names.Add("Amar");
11 names.Add("Pujari");
12 names.Add("Imran");
13 names.Add("karan");
14 foreach (var name in names)
15 {
16 Console.WriteLine(name);
17 }
18 }
19 }

//Output:

Sunil
Amar
Pujari
Imran
karan


Sorted Set

https://www.edureka.co/blog/c-sharp-tutorial/ 23/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

C# SortedSet  class  are often  accustomed  store,  remove  or  read  elements. It maintains ascending order and  doesn’t  store
duplicate elements. it’s prompt to use SortedSet category if you’ve got to store distinctive components and maintain ascending
order. it’s found in System.Collections.Generic namespace.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 var names = new SortedSet<string>();
9 names.Add("Sanjay");
10 names.Add("Anuradha");
11 names.Add("Praveen");
12 names.Add("Ravi");
13 names.Add("Kajol");
14 foreach (var name in names)
15 {
16 Console.WriteLine(name);
17 }
18 }
19 }

//Output:

Anuradha
Kajol
Praveen
Ravi
Sanjay

Stack

The stack is a simple collection that follows FILO or rst in last out procedure while processing the elements stored in it.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 Stack<string> names = new Stack<string>();
9 names.Push("Chandan");
10 names.Push("Pooja");
11 names.Push("James");
12 names.Push("Rajesh");
13 names.Push("kumar");
14 foreach (string name in names)
15 {
16 Console.WriteLine(name);
17 }
18 Console.WriteLine("Peek element: " + names.Peek());
19 Console.WriteLine("Pop: " + names.Pop());
20 Console.WriteLine("After Pop, Peek element: " + names.Peek());
21 }
22 }

//Output:

kumar
Rajesh
James
Pooja
Chandan
Peek element: kumar
Pop: kumar

After Pop, Peek element: Rajesh

https://www.edureka.co/blog/c-sharp-tutorial/ 24/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Queue

The queue is completely similar to Stack but the only di erence is that the Queue follows FIFO or rst in and rst out principle
while processing the elements stored in it.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 Queue<string> names = new Queue<string>();
9 names.Enqueue("Srujan");
10 names.Enqueue("Prajat");
11 names.Enqueue("John");
12 names.Enqueue("Raju");
13 names.Enqueue("Hari");
14 foreach (string name in names)
15 {
16 Console.WriteLine(name);
17 }
18 Console.WriteLine("Peek element: " + names.Peek());
19 Console.WriteLine("Dequeue: " + names.Dequeue());
20 Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
21 }
22 }

//Output:

Srujan
Prajat
John
Raju
Hari
Peek element: Srujan
Dequeue: Srujan
After Dequeue, Peek element: Prajat

Linked List

The linked list is a dynamic memory collection. The elements in the Linked list are stored by accessing the memory from the heap
and storing the elements in a continuous order by linking their addresses.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 var names = new LinkedList<string>();
9 names.AddLast("Rajat");
10 names.AddLast("Arun");
11 names.AddLast("Prakash");
12 names.AddLast("jay");
13 names.AddFirst("sai");
14 foreach (var name in names)
15 {
16 Console.WriteLine(name);
17 }
18 }
19 }

//Output:

https://www.edureka.co/blog/c-sharp-tutorial/ 25/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

sai
Rajat
Arun
Prakash
jay

Dictionary

Dictionary category uses the idea of the hashtable. It stores values on the premise of the key. It contains distinctive keys solely.
By the assistance of key, we will simply search or take away elements. it’s found in System.Collections.Generic namespace.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 Dictionary<string, string> names = new Dictionary<string, string>();
9 names.Add("1", "Shiva");
10 names.Add("2", "Prasad");
11 names.Add("3", "Preetam");
12 names.Add("4", "Roy");
13 names.Add("5", "Akash");
14 foreach (KeyValuePair<string, string> kv in names)
15 {
16 Console.WriteLine(kv.Key + " " + kv.Value);
17 }
18 }
19 }

//Output:

1 Shiva
2 Prasad
3 Preetam
4 Roy
5 Akash

Sorted Dictionary

The SortedDictionary  category  uses the  conception  of the hashtable. It stores values on  the idea  of the key. It
contains distinctive keys and maintains ascending order on the idea of the key. By the assistance  of key,  we will  simply  search
or take away elements. it’s found in System.Collections.Generic namespace.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 SortedDictionary<string, string> names = new SortedDictionary<string, string>();
9 names.Add("1", "Arun");
10 names.Add("4", "Vishal");
11 names.Add("5", "Ramesh");
12 names.Add("3", "Vidya");
13 names.Add("2", "Pallavi");
14 foreach (KeyValuePair<string, string> kv in names)
15 {
16 Console.WriteLine(kv.Key + " " + kv.Value);
17 }
18 }
19 }


//Output:

https://www.edureka.co/blog/c-sharp-tutorial/ 26/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 Shiva
2 Prasad
3 Preetam
4 Roy
5 Akash

Sorted List

The SortedList is  an  array of key/value pairs. It stores values on  the premise  of the key. The
SortedList  category  contains  distinctive  keys and maintains ascending order on  the premise  of the key. By  the assistance  of
key, we are able to simply search or remove elements. it’s found in System.Collections.Generic namespace.

Example:

1 using System;
2 using System.Collections.Generic;
3
4 public class Edureka
5 {
6 public static void Main(string[] args)
7 {
8 SortedDictionary<string, string> names = new SortedDictionary<string, string>();
9 names.Add("1", "Arun");
10 names.Add("4", "Vishal");
11 names.Add("5", "Ramesh");
12 names.Add("3", "Vidya");
13 names.Add("2", "Pallavi");
14 foreach (KeyValuePair<string, string> kv in names)
15 {
16 Console.WriteLine(kv.Key + " " + kv.Value);
17 }
18 }
19 }

//Output:

1 Arun
2 Pallavi
3 Vidya
4 Vishal
5 Ramesh

Structure

The structure is a user-de ned datatype designed to store multiple elements of the di erent datatype. The structure is declared
using the keyword struct.

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 27/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2
3 struct Books
4 {
5 public string title;
6 public string author;
7 public string subject;
8 public int book_id;
9 };
10
11 public class Edureka
12 {
13 public static void Main(string[] args)
14 {
15 Books Book1;
16 Books Book2;
17 Book1.title = "C# Programming";
18 Book1.author = "Ramchandra Kumar";
19 Book1.subject = "C++ Programming Tutorial";
20 Book1.book_id = 95908978;
21 Book2.title = "Telecom Billing";
22 Book2.author = "Karan";
23 Book2.subject = "Telecom Billing Tutorial";
24 Book2.book_id = 18674900;
25 Console.WriteLine("Book 1 title: {0}", Book1.title);
26 Console.WriteLine("Book 1 Author: {0}", Book1.author);
27 Console.WriteLine("Book 1 subject: {0}", Book1.subject);
28 Console.WriteLine("Book 1 book_id:{0}", Book1.book_id);
29 Console.WriteLine("Book 2 title: {0}", Book2.title);
30 Console.WriteLine("Book 2 Author: {0}", Book2.author);
31 Console.WriteLine("Book 2 subject: {0}", Book2.subject);
32 Console.WriteLine("Book 2 book_id: {0}", Book2.book_id);
33 Console.ReadKey();
34 }
35 }

//Output:

Book 1 title: C# Programming


Book 1 Author: Ramchandra Kumar
Book 1 subject: C++ Programming Tutorial
Book 1 book_id :95908978
Book 2 title: Telecom Billing
Book 2 Author: Karan
Book 2 subject: Telecom Billing Tutorial
Book 2 book_id: 18674900

Functions

The function is de ned as a block of code of the main code. The function is used to execute statements speci ed in the code
block. A function consists of the following components.

Function name: It is a distinctive name that is used to make a Function call.


Return type: It speci es the data type of function return value.
Body: It contains executable statements.
Access speci er: It speci es function accessibility in the application.
Parameters: It is a list of arguments that we can pass to the function during the call.

Syntax

1 <access-specifier><return-type>FunctionName(<parameters>)
2 {
3 // function body
4 // return statement
5 }

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 28/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 namespace FunctionExample
3 {
4 class Edureka
5 {
6 public string Show(string message)
7 {
8 Console.WriteLine("Inside Show Function");
9 return message;
10 }
11 static void Main(string[] args)
12 {
13 Edureka program = new Edureka();
14 string message = program.Show("To Edureka");
15 Console.WriteLine("Welcome " + message);
16 }
17 }
18 }

//Output:

Inside Show Function


Welcome To Edureka

Functions can be executed in 3 di erent ways:

Call by Value
Call by Reference
Out Parameter

Call by Value

In C#, value-type parameters are that pass a replica of original value to the function instead of reference. It doesn’t modify the


rst  value. An  amendment  created  in passed  value  doesn’t  alter  the particular  value.  within the  following example,  we’ve
got pass value throughout the call.

Example:

1 using System;
2 namespace CallByValue
3 {
4 class Edureka
5 {
6 public void Show(int val)
7 {
8 val *= val;
9 Console.WriteLine("The value inside the show function " + val);
10 }
11 static void Main(string[] args)
12 {
13 int val = 50;
14 Edureka program = new Edureka();
15 Console.WriteLine("Value before calling the function " + val);
16 program.Show(val);
17 Console.WriteLine("Value after calling the function " + val);
18 }
19 }
20 }

//Output:

Value before calling the function 50


The value inside the show function 2500
Value after calling the function 50

Call by Reference

In Call by Reference method,  a ref keyword to pass the argument as reference-type. It passes the reference of arguments to the
function rather than a copy of the original value. The changes in passed values are permanent and modify the original variable
value.

Example: 

https://www.edureka.co/blog/c-sharp-tutorial/ 29/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 namespace CallByReference
3 {
4 class Edureka
5 {
6 public void Show(ref int val)
7 {
8 val *= val;
9 Console.WriteLine("The value inside the show function " + val);
10 }
11 static void Main(string[] args)
12 {
13 int val = 50;
14 Edureka program = new Edureka();
15 Console.WriteLine("Value before calling the function " + val);
16 program.Show(ref val);
17 Console.WriteLine("Value after calling the function " + val);
18 }
19 }
20 }

//Output:

Value before calling the function 50


The value inside the show function 2500
Value after calling the function 2500

Out Parameter

The Out Parameter provides out keyword to pass arguments as out-type. It is like reference-type, except that it does not require
the variable to initialize before passing. We must use out keyword to pass the argument as out-type. It is useful when we want a
function to return multiple values.

Example:

1 using System;
2 namespace OutParameter
3 {
4 class Edureka
5 {
6 public void Show(out int val)
7 {
8 int square = 5;
9 val = square;
10 val *= val;
11 }
12 static void Main(string[] args)
13 {
14 int val = 50;
15 Edureka program = new Edureka();
16 Console.WriteLine("Value before passing out variable " + val);
17 program.Show(out val);
18 Console.WriteLine("Value after recieving the out variable " + val);
19 }
20 }
21 }

//Output:

Value before passing out variable 50

Valueafter recieving the out variable 25

Now let us move to Object-oriented programming

Object-Oriented Programming 

Object-oriented programming  System  is a programming paradigm based on the concept of  objects  that contain  data 
members and methods related to them. The primary purpose of object-oriented programming is to increase the exibility and
maintainability of programs

https://www.edureka.co/blog/c-sharp-tutorial/ 30/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Features of object-oriented programming:


It emphasis more on data rather than procedure.
The programs are divided into objects thus making it easy to work with.
Data structures are designed in such a way that they characterize the objects.
Functions that work on the data of an object are placed together in the data structure.
Data is hidden and cannot be accessed by external functions without permission.
Communication between objects can take place with the help of functions.
Adding new data and functions has become easy.
Follows the bottom-up approach in program design.

The Object-Oriented Paradigms in C# are as follows

Enumeration in C#
Object-Oriented Programming Approach
Encapsulation
Abstraction
Interface
Polymorphism
Inheritance
Overloading and Overriding
Namespace
File Operations
Events
Generics
Delegates
Re ection

Enumeration in C#

Enum or also called as an enumeration in C# is used to store constant values without having to alter them during the entire
execution of a C# Program. It is used to store a set of named constants such as season, days, month, size etc

Example:

1 using System;
2 public class EnumExample
3 {
4 public enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
5 public static void Main()
6 {
7 int x = (int)week.Monday;
8 int y = (int)week.Friday;
9 Console.WriteLine("Monday = {0}", x);
10 Console.WriteLine("Friday = {0}", y);
11 }
12 }

//Output:

Monday = 0
Friday = 4

Object-Oriented Programming Approach

The Object-Oriented style of programming can be achieved by following the methods prescribed below.

Encapsulation


Encapsulation is a method to combine the methods along with their data members.

https://www.edureka.co/blog/c-sharp-tutorial/ 31/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Example:

1 using System;
2
3 namespace Edureka
4 {
5 class Rectangle
6 {
7 public double length;
8 public double width;
9 public double GetArea()
10 {
11 return length * width;
12 }
13 public void Display()
14 {
15 Console.WriteLine("Length: {0}", length);
16 Console.WriteLine("Width: {0}", width);
17 Console.WriteLine("Area: {0}", GetArea());
18 }
19 }
20 class ExecuteRectangle
21 {
22 static void Main(string[] args)
23 {
24 Rectangle r = new Rectangle();
25 r.length = 50;
26 r.width = 35;
27 r.Display();
28 Console.ReadLine();
29 }
30 }
31 }

//Output:

Length: 50
Width: 35
Area: 1750

Abstraction

Abstraction is a method to hide the complex coding part from the user by providing him with only the required information he
needs.

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 32/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 public abstract class Shape
3 {
4 public abstract void draw();
5 }
6 public class Rectangle : Shape
7 {
8 public override void draw()
9 {
10 Console.WriteLine("drawing rectangle...");
11 }
12 }
13 public class Circle : Shape
14 {
15 public override void draw()
16 {
17 Console.WriteLine("drawing circle...");
18 }
19 }
20 public class TestAbstract
21 {
22 public static void Main()
23 {
24 Shape s;
25 s = new Rectangle();
26 s.draw();
27 s = new Circle();
28 s.draw();
29 }
30 }

//Output:

drawing rectangle...
drawing circle...

Interface

The interface is completely similar to Abstraction. The Functionality of an Interface is to hide the unimportant data from the user
and provide him with the only important data he needs.

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 33/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 public interface Drawable
3 {
4 void draw();
5 }
6 public class Rectangle : Drawable
7 {
8 public void draw()
9 {
10 Console.WriteLine("drawing rectangle...");
11 }
12 }
13 public class Circle : Drawable
14 {
15 public void draw()
16 {
17 Console.WriteLine("drawing circle...");
18 }
19 }
20 public class TestInterface
21 {
22 public static void Main()
23 {
24 Drawable d;
25 d = new Rectangle();
26 d.draw();
27 d = new Circle();
28 d.draw();
29 }
30 }

//Output:

drawing rectangle...
drawing circle...

Polymorphism

Polymorphism is the combination of “poly” + “morphs” which means many forms. It is a greek word. It means the code segment
can take up multiple forms. We have two types of Polymorphism.

Compile Time Polymorphism


Run Time Polymorphism 

Example:

1 using System;
2 public class Animal
3 {
4 public string color = "white";
5 }
6 public class Dog : Animal
7 {
8 public string color = "black";
9 }
10 public class TestSealed
11 {
12 public static void Main()
13 {
14 Animal d = new Dog();
15 Console.WriteLine(d.color);
16
17 }
}

//Output:
https://www.edureka.co/blog/c-sharp-tutorial/ 34/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

white

Inheritance

Inheritance is a process in which one object acquires all the properties and behaviours of its parent object automatically. You
can reuse, extend or modify the attributes and behaviours which is de ned in other class. the class which inherits the members
of another class is called derived class and the class whose members are inherited is called the base class. The derived class is
the specialized class for the base class.

Example for Single Level Inheritance

1 using System;
2 namespace RectangleApplication
3 {
4 class Rectangle
5 {
6 protected double length;
7 protected double width;
8 public Rectangle(double l, double w)
9 {
10 length = l;
11 width = w;
12 }
13 public double GetArea()
14 {
15 return length * width;
16 }
17 public void Display()
18 {
19 Console.WriteLine("Length: {0}", length);
20 Console.WriteLine("Width: {0}", width);
21 Console.WriteLine("Area: {0}", GetArea());
22 }
23 }
24 class Tabletop : Rectangle
25 {
26 private double cost;
27 public Tabletop(double l, double w) : base(l, w) { }
28 public double GetCost()
29 {
30 double cost;
31 cost = GetArea() * 70;
32 return cost;
33 }
34 public void Display()
35 {
36 base.Display();
37 Console.WriteLine("Cost: {0}", GetCost());
38 }
39 }
40 class ExecuteRectangle
41 {
42 static void Main(string[] args)
43 {
44 Tabletop t = new Tabletop(4.5, 7.5);
45 t.Display();
46 Console.ReadLine();
47 }
48 }
49 }

//Output:

Length: 4.5
Width: 7.5

Area: 33.75

https://www.edureka.co/blog/c-sharp-tutorial/ 35/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Cost: 2362.5

Example of Multi-Level Inheritance

1 using System;
2
3 namespace InheritanceApplication
4 {
5 class Shape
6 {
7 public void setWidth(int w)
8 {
9 width = w;
10 }
11 public void setHeight(int h)
12 {
13 height = h;
14 }
15 protected int width;
16 protected int height;
17 }
18 public interface PaintCost
19 {
20 int getCost(int area);
21 }
22 class Rectangle : Shape, PaintCost
23 {
24 public int getArea()
25 {
26 return (width * height);
27 }
28 public int getCost(int area)
29 {
30 return area * 70;
31 }
32 }
33 class RectangleTester
34 {
35 static void Main(string[] args)
36 {
37 Rectangle Rect = new Rectangle();
38 int area;
39 Rect.setWidth(5);
40 Rect.setHeight(7);
41 area = Rect.getArea();
42 Console.WriteLine("Total area: {0}", Rect.getArea());
43 Console.WriteLine("Total paint cost: ${0}", Rect.getCost(area));
44 Console.ReadKey();
45 }
46 }
47 }

//Output:

Total area: 35
Total paint cost: $2450

Overloading 

Overloading is a situation where we have two or members declared using the same name. Overloading is also possible when we
declare two or more methods with the same name as well. Let us check examples of both.

Member Overloading

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 36/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 public class Edureka
3 {
4 public static int add(int a, int b)
5 {
6 return a + b;
7 }
8 public static int add(int a, int b, int c)
9 {
10 return a + b + c;
11 }
12 }
13 public class TestMemberOverloading
14 {
15 public static void Main()
16 {
17 Console.WriteLine(Edureka.add(12, 23));
18 Console.WriteLine(Edureka.add(12, 23, 25));
19 }
20 }

//Output:

35
60

Method Overloading

Example:

1 using System;
2 public class Edureka
3 {
4 public static int add(int a, int b)
5 {
6 return a + b;
7 }
8 public static float add(float a, float b)
9 {
10 return a + b;
11 }
12 }
13 public class TestMemberOverloading
14 {
15 public static void Main()
16 {
17 Console.WriteLine(Edureka.add(12, 23));
18 Console.WriteLine(Edureka.add(12.4f, 21.3f));
19 }
20 }

//Output:

35
33.699997

Overriding

Overriding is a situation where child class de nes the same method which the parent is de ning as well. Let us understand this
through a small example.

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 37/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 public class Edureka
3 {
4 public virtual void eat()
5 {
6 Console.WriteLine("Eating ");
7 }
8 }
9 public class Dog : Edureka
10 {
11 public override void eat()
12 {
13 Console.WriteLine("Eating food");
14 }
15 }
16 public class Overriding
17 {
18 public static void Main()
19 {
20 Dog d = new Dog();
21 d.eat();
22 }
23 }

//Output:

Eating food

Namespace

The namespace is basically used to handle multiple classes present in the program. The namespace is available in di erent
ways.

System.Console: Here, the System becomes the namespace


To access the class of a namespace, we need to use namespacename.classname.
We can use the using keyword as well.

Example:

1 using System;
2 using First;
3 using Second;
4 namespace First
5 {
6 public class Edureka
7 {
8 public void sayWelcome() { Console.WriteLine("Welcome To Edureka"); }
9 }
10 }
11 namespace Second
12 {
13 public class Happy_Learning
14 {
15 public void sayWishes() { Console.WriteLine("Happy Learning"); }
16 }
17 }
18 public class Namespace
19 {
20 public static void Main()
21 {
22 Edureka h1 = new Edureka();
23 Happy_Learning w1 = new Happy_Learning();
24 h1.sayWelcome();
25 w1.sayWishes();
26 }
27 }

//Output:

Welcome To Edureka
Happy Learning

File Operations

The le operations available in C# are as follows:

https://www.edureka.co/blog/c-sharp-tutorial/ 38/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Operation Description
 BinaryReader Reads primitive data from a binary stream.
 BinaryWriter Writes primitive data in binary format.
 Bu eredStream Temporary storage for a stream of bytes.
 Directory Helps in manipulating a directory structure.
DirectoryInfo Used for performing operations on directories.
 DriveInfo Provides information for the drives.
 File Helps in manipulating les.
 FileInfo Used for performing operations on les.
 FileStream Used to read from and write to any location in a le.
MemoryStream  Used for random access to streamed data stored in memory.
 Path Performs operations on path information.
 StreamReader Used for reading characters from a byte stream.
 StreamWriter Is used for writing characters to a stream.
 StringReader Is used for reading from a string bu er.
 StringWriter Is used for writing into a string bu er.

FileMode

The FileMode is an enumerator which de nes multiple le opening methods. The members of the FileMode Enumerator are
described as follows:

Append: It opens an existing le and puts the cursor at the end of le, or creates the le if the le does not exist.
Create: It is designed to create a new le.
CreateNew: It is designed to specify to the operating system, that it should create a new le.
Open: It is designed to open an existing le.
OpenOrCreate: It is designed to specify the operating system that it should open a le if it exists, otherwise it should create
a new le.
Truncate: Truncate opens an existing le and truncates its size to zero bytes.

FileAccess

FileAccess Enumerator is used to gaining access to a particular le. It has the following members.

Read
Write
ReadWrite

FileShare

The Fileshare Enumerator is used to share a particular le. It has the following members.

Inheritable: Inheritable allows a lehandle to pass an inheritance to the child processes.


None: None declines sharing of the current le
Read: Read allows opening the le for reading.
ReadWrite: ReadWrite allows opening the le for reading and writing.
Write: Write allows opening the le for writing.

Events

An Event is generally known as an action that is generated by the user. It might be a click of the mouse and even a single
keystroke from the keyboard. Similarly, C# programs also have events. The generator of the event is called the publisher and the
receiver of the event is called the subscriber.

Publisher

A publisher  contains the de nition of the event and the delegate. The event-delegate association is de ned in this object. A
publisher class object invokes the event and it is noti ed to other objects.


Subscriber

A subscriber accepts the event and provides an event handler. The delegate in the publisher class invokes the method /event
handler of the subscriber class.

https://www.edureka.co/blog/c-sharp-tutorial/ 39/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Example:

1 using System;
2
3 namespace Edureka
4 {
5 public delegate string Del(string str);
6 class EventBlock
7 {
8 event Del NewEvent;
9 public EventBlock()
10 {
11 this.NewEvent += new Del(this.WelcomeUser);
12 }
13 public string WelcomeUser(string username)
14 {
15 return "Welcome To Edureka. " + username;
16 }
17 static void Main(string[] args)
18 {
19 EventBlock obj1 = new EventBlock();
20 string result = obj1.NewEvent("Happy Learning");
21 Console.WriteLine(result);
22 }
23 }
24 }

//Output:

Welcome To Edureka. Happy Learning

Generics

Generics is a concept of providing the members and methods of a class with place holders in Run-time. We can de ne Generics
using <> brackets. Let us check out the following examples.

Generics in a Class

1 using System;
2 namespace Edureka
3 {
4 class GenericClass<T>
5 {
6 public GenericClass(T msg)
7 {
8 Console.WriteLine(msg);
9 }
10 }
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 GenericClass<string> gen = new GenericClass<string>("This message is from generic class");
16 GenericClass<int> genI = new GenericClass<int>(123);
17 GenericClass<char> getCh = new GenericClass<char>('E');
18 }
19 }
20 }

//Output:

This message is from generic class


123
E

Generics in a Method

https://www.edureka.co/blog/c-sharp-tutorial/ 40/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 namespace Edureka
3 {
4 class GenericClass
5 {
6 public void Show<T>(T msg)
7 {
8 Console.WriteLine(msg);
9 }
10 }
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 GenericClass genC = new GenericClass();
16 genC.Show("This message is from the generic method");
17 genC.Show(321);
18 genC.Show('H');
19 }
20 }
21 }

//Output:

This message is from the generic method


321
H

Delegates

The Delegate acts as a reference to the method. Basically it’s same as a function pointer in C and C++ but far better and type-
safe. The Delegate in static method encapsulates method only. While the delegate in the instance method encapsulates both
method and instance. The best use of delegate is to use as an event.

Example:

1 using System;
2 delegate int Calculator(int n);
3 public class Edureka
4 {
5 static int number = 25;
6 public static int add(int n)
7 {
8 number = number + n;
9 return number;
10 }
11 public static int mul(int n)
12 {
13 number = number * n;
14 return number;
15 }
16 public static int getNumber()
17 {
18 return number;
19 }
20 public static void Main(string[] args)
21 {
22 Calculator c1 = new Calculator(add);
23 Calculator c2 = new Calculator(mul);
24 c1(20);
25 Console.WriteLine("After calculator one delegate, the new Number is: " + getNumber());
26 c2(3);
27 Console.WriteLine("After calculator two delegate, the new Number is: " + getNumber());
28 }
29 }

//Output:

After calculator one delegate, the new Number is: 45


After calculator two delegate, the new Number is: 135

Re ection

The Re ection is required to obtain the metadata in run-time. The Reference is available in System.Re ection namespace. It

requires the following classes to execute.

https://www.edureka.co/blog/c-sharp-tutorial/ 41/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Type
MemberInfo
ConstructorInfo
MethodInfo
FieldInfo
PropertyInfo
TypeInfo
EventInfo
Module
Assembly
AssemblyName
Pointer

Type class

C# Type class represents type declarations for class types, interface types, enumeration types, array types, value types

Type Properties
A list of important properties of Type classes is mentioned below.

Property Description
Assembly Gets the Assembly for this type.
AssemblyQuali edName Gets the Assembly quali ed name for this type.
Attributes Gets the Attributes associated with the type.
BaseType Gets the base or parent type.
FullName Gets the fully quali ed name of the type.
 IsAbstract is used to check if the type is Abstract.
 IsArray is used to check if the type is Array.
 IsClass is used to check if the type is Class.
 IsEnum is used to check if the type is Enum.
IsInterface is used to check if the type is Interface.
 IsNested is used to check if the type is Nested.
 IsPrimitive is used to check if the type is Primitive.
 IsPointer is used to check if the type is Pointer.
 IsNotPublic is used to check if the type is not Public.
IsPublic is used to check if the type is Public.
 IsSealed is used to check if the type is Sealed.
 IsSerializable is used to check if the type is Serializable.
 MemberType is used to check if the type is Member type of Nested type.
 Module Gets the module of the type.
 Name Gets the name of the type.
Namespace Gets the namespace of the type.

Property Description
GetConstructors() Returns all the public constructors for the Type.
GetConstructors(BindingFlags) Returns all the constructors for the Type with speci ed BindingFlags.
GetFields() Returns all the public elds for the Type.
GetFields(BindingFlags) Returns all the public constructors for the Type with speci ed BindingFlags.
GetMembers() Returns all the public members for the Type.
GetMembers(BindingFlags)   Returns all the members for the Type with speci ed BindingFlags.
GetMethods() Returns all the public methods for the Type.
GetMethods(BindingFlags) Returns all the methods for the Type with speci ed BindingFlags.
GetProperties() Returns all the public properties for the Type.
GetProperties(BindingFlags) Returns all the properties for the Type with speci ed BindingFlags.
GetType()
GetType(String)
Gets the current Type.
Gets the Type for the given name.

https://www.edureka.co/blog/c-sharp-tutorial/ 42/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Re ection Examples:

Get Type

Example:

1 using System;
2 public class GetType
3 {
4 public static void Main()
5 {
6 int a = 10;
7 Type type = a.GetType();
8 Console.WriteLine(type);
9 }
10 }

//Output:

System.Int32

Get Assembly

Example:

1 using System;
2 using System.Reflection;
3 public class GetAssembly
4 {
5 public static void Main()
6 {
7 Type t = typeof(System.String);
8 Console.WriteLine(t.Assembly);
9 }
10 }

//Output:

System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Print Type Information

Example:

1 using System;
2 using System.Reflection;
3 public class PrintType
4 {
5 public static void Main()
6 {
7 Type t = typeof(System.String);
8 Console.WriteLine(t.FullName);
9 Console.WriteLine(t.BaseType);
10 Console.WriteLine(t.IsClass);
11 Console.WriteLine(t.IsEnum);
12 Console.WriteLine(t.IsInterface);
13 }
14 }

//Output:

True
False
False

Print Constructors

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 43/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 using System.Reflection;
3 public class PrintConstructors
4 {
5 public static void Main()
6 {
7 Type t = typeof(System.String);
8 Console.WriteLine("Constructors of {0} type...", t);
9 ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
10 foreach (ConstructorInfo c in ci)
11 {
12 Console.WriteLine(c);
13 }
14 }
15 }

//Output:

Constructors of System.String type...


Void .ctor(Char[])
Void .ctor(Char[], Int32, Int32)
Void .ctor(Char*)
Void .ctor(Char*, Int32, Int32)
Void .ctor(SByte*)
Void .ctor(SByte*, Int32, Int32)
Void .ctor(SByte*, Int32, Int32, System.Text.Encoding)
Void .ctor(Char, Int32)
Void .ctor(System.ReadOnlySpan`1[System.Char])

Print Methods

Example:

1 using System;
2 using System.Reflection;
3 public class PrintMethods
4 {
5 public static void Main()
6 {
7 Type t = typeof(System.String);
8 Console.WriteLine("Methods of {0} type...", t);
9 MethodInfo[] ci = t.GetMethods(BindingFlags.Public | BindingFlags.Instance);
10 foreach (MethodInfo m in ci)
11 {
12 Console.WriteLine(m);
13 }
14 }
15 }

//Output:

Methods of System.String type...


System.String Replace(System.String, System.String)
System.String[] Split(Char, System.StringSplitOptions)
System.String[] Split(Char, Int32, System.StringSplitOptions)
System.String[] Split(Char[])
System.String[] Split(Char[], Int32)
System.String[] Split(Char[], System.StringSplitOptions)
System.String[] Split(Char[], Int32, System.StringSplitOptions)
System.String[] Split(System.String, System.StringSplitOptions)
System.String[] Split(System.String, Int32, System.StringSplitOptions)
System.String[] Split(System.String[], System.StringSplitOptions)
System.String[] Split(System.String[], Int32, System.StringSplitOptions)......

Print Fields

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 44/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 using System.Reflection;
3 public class PrintFields
4 {
5 public static void Main()
6 {
7 Type t = typeof(System.String);
8 Console.WriteLine("Fields of {0} type...", t);
9 FieldInfo[] ci = t.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPubl
10 foreach (FieldInfo f in ci)
11 {
12 Console.WriteLine(f);
13 }
14 }
15 }

//Output:

Fields of System.String type...


System.String Empty

Now, let us move on to some advanced C# Programming Concepts

Advanced C# Concepts
Anonymous Function
Multi-Threading
Exception Handling
Synchronization
New Features

Anonymous Function

The Function that lacks a speci c name is called Anonymous Functions. There are two types of Anonymous Functions available
in C#

Lambda Expressions
Anonymous Methods

Example:

1 using System;
2 namespace LambdaExpressions
3 {
4 class Edureka
5 {
6 delegate int Square(int num);
7 static void Main(string[] args)
8 {
9 Square GetSquare = x => x * x;
10 int j = GetSquare(25);
11 Console.WriteLine("Square: " + j);
12 }
13 }
14 }

//Output:

Square: 625

Anonymous Methods

The anonymous method provides the same functionality as a lambda expression, except that it allows us to ignore the
parameter list.

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 45/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 namespace AnonymousMethods
3 {
4 class Program
5 {
6 public delegate void AnonymousFun();
7 static void Main(string[] args)
8 {
9 AnonymousFun fun = delegate () {
10 Console.WriteLine("This is anonymous function");
11 };
12 fun();
13 }
14 }
15 }

//Output:

This is anonymous function

Multi-Threading

Multithreading is a process where multiple threads are created and assigned for di erent tasks. this saves time by executing
multiple jobs at a time. The multithreading class is available in System.Threading namespace.

System.Threading Namespace

The System.Threading namespace contains classes and interfaces to facilitate multithreading. It provides classes to synchronize
the thread resource. A list of commonly used classes are given below:

Thread
Mutex
Timer
Monitor
Semaphore
ThreadLocal
ThreadPool
Volatile

Process and thread

The Process is actually and application and it is considered to be a heavyweight component. On the other hand, The thread is
one single module of the whole application. It is lightweight compared to the process

The LifeCycle of a Thread

Each Thread has a Life Cycle. The Life Cycle of the thread is de ned in System.Threading.Thread class. The following are the
stages in the Life Cycle of any thread.

Unstarted
Runnable (Ready to run)
Running
Not Runnable
Dead

The Thread class provides the following properties and methods as follows.

Thread Properties

Property Description
CurrentThread returns the instance of currently running thread.
IsAlive checks whether the current thread is alive or not.
IsBackground To get/set value of current thread is in the background or not.
ManagedThreadId is used to get the unique id for the currently managed thread.
Name is used to get or set the name of the current thread.
Priority is used to get or set the priority of the current thread. 
ThreadState is used to return a value representing the thread state.

https://www.edureka.co/blog/c-sharp-tutorial/ 46/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Thread Methods

Method Description
Abort() is used to terminate the thread. It raises ThreadAbortException.
Interrupt() is used to interrupt a thread which is in WaitSleepJoin state.
Join() is used to block all the calling threads until this thread terminates.
ResetAbort() is used to cancel the Abort request for the current thread.
Resume() is used to resume the suspended thread. It is obsolete.
Sleep(Int32) is used to suspend the current thread for the speci ed milliseconds.
Start() changes the current state of the thread to Runnable.
Suspend() suspends the current thread if it is not suspended. It is obsolete.
Yield() is used to yield the execution of the current thread to another thread.

Main Thread Example

1 using System;
2 using System.Threading;
3 public class Edureka
4 {
5 public static void Main(string[] args)
6 {
7 Thread t = Thread.CurrentThread;
8 t.Name = "MainThread";
9 Console.WriteLine(t.Name);
10 }
11 }

//Output:

MainThread

Exception Handling

The exception is an error thrown by the program in its run-time. We perform Exception-Handling in order to make our program
exception free.

Exception Description
System.DivideByZeroException Error generated by dividing a number with zero.
System.NullReferenceException handles the error generated by referencing the null object.
System.InvalidCastException handles the error generated by invalid typecasting.
System.IO.IOException handles the Input/Output errors.
System.FieldAccessException Error generated by invalid private/protected access.

In C#, we use 4 keywords to perform exception handling:

try
catch
nally, and
throw

Example:

https://www.edureka.co/blog/c-sharp-tutorial/ 47/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

1 using System;
2 public class EdurekExample
3 {
4 public static void Main(string[] args)
5 {
6 try
7 {
8 int a = 10;
9 int b = 0;
10 int x = a / b;
11 }
12 catch (Exception e)
13 {
14 Console.WriteLine(e);
15 }
16 Console.WriteLine("This message is from catch block");
17 }
18 }

//Output:

System.DivideByZeroException: Attempted to divide by zero.


at ExExaEdurekample.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 10
This message is from catch block

Customized Exception Example

1 using System;
2 public class InvalidAgeException : Exception
3 {
4 public InvalidAgeException(String message): base(message)
5 {
6 }
7 }
8 public class Customized
9 {
10 static void validate(int age)
11 {
12 if (age < 18)
13 {
14 throw new InvalidAgeException("Sorry, Age is expected to be greater than 18");
15 }
16 }
17 public static void Main(string[] args)
18 {
19 try
20 {
21 validate(12);
22 }
23 catch (InvalidAgeException e)
24 {
25 Console.WriteLine(e);
26 }
27 Console.WriteLine("Catch block is being executed now.");
28 }
29 }

//Output:

InvalidAgeException: Sorry, Age is expected to be greater than 18


at Customized.validate(Int32 age) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 18
at Customized.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 23
Catch block is being executed now.

Finally block example

1 using System;
2 public class FinalExecption
3 {
4 public static void Main(string[] args)
5 {
6 try
7 {
8 int a = 10;
9 int b = 0;
10 int x = a / b;
11 }


12 catch (Exception e) { Console.WriteLine(e); }
13 finally { Console.WriteLine("Finally block is executed"); }
14 Console.WriteLine("Catch block is executed");
15 }
16 }

https://www.edureka.co/blog/c-sharp-tutorial/ 48/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

//Output:

System.DivideByZeroException: Attempted to divide by zero.


at FinalExecption.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 10
Finally block is executed
Catch block is executed

System Exception Signature

1 [SerializableAttribute]
2 [ComVisibleAttribute(true)]
3 public class SystemException : Exception

System Exception Constructors

Constructor Description
SystemException() It is used to initialize a new instance of the SystemException class.
SystemException
It is used to initialize a new instance of the SystemException class with
(SerializationInfo,StreamingConte
serialized data.
xt)

It is used to initialize a new instance of the SystemException class with a


SystemException(String)
speci ed error message.
It is used to initialize a new instance of the SystemException class with a
SystemException(String,Exception) speci ed error message and a reference to the inner exception that is
the cause of this exception.

System Exception Properties

Property Description
It is used to get a collection of key/value pairs that provide additional user-de ned
Data
information about the exception.
HelpLink It is used to get or set a link to the help le associated with this exception.
It is used to get or set HRESULT, a coded numerical value that is assigned to a speci c
HResult
exception.
InnerException It is used to get the Exception instance that caused the current exception.
Message It is used to get a message that describes the current exception.
Source It is used to get or set the name of the application that causes the error.
StackTrace It is used to get a string representation of the immediate frames on the call stack.
TargetSite It is used to get the method that throws the current exception.

System Exception Methods 

Methods Description
It is used to check that the speci ed object is equal to the current object
Equals(Object)
or not.
Finalize() It is used to free resources and perform cleanup operations.
GetBaseException() It is used to get root exception.
GetHashCode() It is used to get the hash code.
GetObjectData

(SerializationInfo,StreamingCo It is used to get object data.


ntext)

GetType() It is used to get the runtime type of the current instance.


MemberwiseClone() It is used to create a shallow copy of the current Object.

ToString()
It is used to create and return a string representation of the current 
exception.

https://www.edureka.co/blog/c-sharp-tutorial/ 49/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

System Exception Example

1 using System;
2 namespace CSharpProgram
3 {
4 class SystemExceptionExample
5 {
6 static void Main(string[] args)
7 {
8 try
9 {
10 int[] arr = new int[5];
11 arr[10] = 25;
12 }
13 catch (SystemException e)
14 {
15 Console.WriteLine(e);
16 }
17 }
18 }
19 }

//Output:

System.IndexOutOfRangeException: Index was outside the bounds of the array.


at CSharpProgram.SystemExceptionExample.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line
11

Synchronization

Synchronization  may be a  technique  that enables  only 1  thread to access the resource for  a speci c  time.
No alternative thread will interrupt until the appointed thread nishes its task.

In multithreading program, threads are allowed to access any resource for the speci ed execution time. Threads share resources
and execute asynchronously. Accessing shared resources (data)may be an important task that generally could halt the system.we
have a tendency to in uence it by creating-threads in a synchronous manner.

Example Without Synchronisation

1 using System;
2 using System.Threading;
3 class Edureka
4 {
5 public void PrintTable()
6 {
7 for (int i = 1; i <= 10; i++)
8 {
9 Thread.Sleep(100);
10 Console.WriteLine(i);
11 }
12 }
13 }
14 class Program
15 {
16 public static void Main(string[] args)
17 {
18 Edureka p = new Edureka();
19 Thread t1 = new Thread(new ThreadStart(p.PrintTable));
20 Thread t2 = new Thread(new ThreadStart(p.PrintTable));
21 t1.Start();
22 t2.Start();
23 }
24 }

//Output:

1
1
2
2
3

3

https://www.edureka.co/blog/c-sharp-tutorial/ 50/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

4
4
5
5
6
6
7
7
8
8
9
9
10
10

Example With Synchronisation

1 using System;
2 using System.Threading;
3 class Edureka
4 {
5 public void PrintTable()
6 {
7 lock (this)
8 {
9 for (int i = 1; i <= 10; i++)
10 {
11 Thread.Sleep(100);
12 Console.WriteLine(i);
13 }
14 }
15 }
16 }
17 class Program
18 {
19 public static void Main(string[] args)
20 {
21 Edureka p = new Edureka();
22 Thread t1 = new Thread(new ThreadStart(p.PrintTable));
23 Thread t2 = new Thread(new ThreadStart(p.PrintTable));
24 t1.Start();
25 t2.Start();
26 }
27 }

//Output:

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7

https://www.edureka.co/blog/c-sharp-tutorial/ 51/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

8
9
10

New Features

Microsoft has added many latest features to C# language some of them are mentioned below.

C# 6.0
Using static directive
Exception lters
Await in catch/ nally blocks
Auto property initializers
Default values for getter-only properties
Expression-bodied members
Null propagator
String interpolation
Nameof operator
Dictionary initializer
Compiler-as-a-service (Roslyn)

C# 7.0
Pattern matching
Tuples
Deconstruction
Local functions
Digit separator
Binary literals
Ref returns and locals
Expression bodied constructors and nalizers
Expression bodied getters and setters
Out variables
Generalized async return types

C# 7.1
Async main
Default expressions

Interview Questions based on C#


The important interview Questions based on C# Programming Language can be found in this updated Article.

With this, we come to an end of this “C# Tutorial” article. I hope you have understood the importance of Data Structures, Syntax,
functionality, and operations performed using them.  Now that you have understood the basics of Programming in C# through
this C# Tutorial, check out the java training provided by Edureka on many technologies like Java,  Spring  and many more, a
trusted online learning company with a network of more than 250,000 satis ed learners spread across the globe got a question
for us? Mention it in the comments section of this “C# Tutorial” blog and we will get back to you as soon as possible.

Recommended blogs for you

Vol. I – Edureka Career Watch –


12th Jan. 2019
Vol. XX – Edureka Career
Watch – 21st Sep 2019
Recurrent Neural Networks
(RNN) Tutorial | Analyzing
Sequential Data Using
Responsibilities
RPA Developer Roles

TensorFlow In Python

https://www.edureka.co/blog/c-sharp-tutorial/ 52/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Read Article Read Article Read Article Read Article

‹›

Comments 0 Comments

ALSO ON HTTPS://WWW.EDUREKA.CO/BLOG/

Why Java is Secure? Top 50 Networking How to Get Started How To Install Introduction to
Top 10 Java … Interview Questions … With Your Web … MongoDB on Mac … Programming

3 months ago • 1 comment 4 months ago • 1 comment 4 months ago • 2 comments 4 months ago • 1 comment 4 months ago • 1
As you all are well aware The knowledge of According to TechRepublic, In our previous article we There are 2.72 m
that Java is a vast world. Networking is the most web development is one of talked about how you can available in the fi
There are a lot of … crucial requirement for … the 10 hottest tech skills … install MongoDB … science. R and P

0 Comments https://www.edureka.co/blog/ 
1 Login

 Recommend t Tweet f Share Sort by Best

Start the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Be the first to comment.

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy

Trending Courses

DevOps Certi cation Python Certi cation Training AWS Architect Certi cation Cybersecurity Cer
Training for Data Scienc ... Training Course
 64k Enrolled Learners  57k Enrolled Learners  65k Enrolled Learners  14k Enrolled Learne
 Weekend/Weekday  Weekend/Weekday  Weekend/Weekday  Weekend
 Live Class  Live Class  Live Class  Live Class

Reviews Reviews Reviews Reviews

 5 (25250)  5 (22600)  5 (26000)  5 (5300)

‹›
Browse Categories

Arti cial Intelligence BI and Visualization Big Data Blockchain Cloud Computing Cyber Security Data Science

Data Warehousing and ETL Databases DevOps Digital Marketing Front End Web Development Mobile Development

https://www.edureka.co/blog/c-sharp-tutorial/ 53/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

Operating Systems Programming & Frameworks Project Management and Methodologies Robotic Process Automation Software Testing

Systems & Architecture


TRENDING CERTIFICATION COURSES TRENDING MASTERS COURSES

DevOps Certi cation Training Data Scientist Masters Program

AWS Architect Certi cation Training DevOps Engineer Masters Program

Big Data Hadoop Certi cation Training Cloud Architect Masters Program

Tableau Training & Certi cation Big Data Architect Masters Program

Python Certi cation Training for Data Science Machine Learning Engineer Masters Program

Selenium Certi cation Training Full Stack Web Developer Masters Program

PMP® Certi cation Exam Training Business Intelligence Masters Program

Robotic Process Automation Training using UiPath Data Analyst Masters Program

Apache Spark and Scala Certi cation Training Test Automation Engineer Masters Program

Microsoft Power BI Training Post-Graduate Program in Arti cial Intelligence & Machine Learning

Online Java Course and Training Post-Graduate Program in Big Data Engineering

Python Certi cation Course

COMPANY WORK WITH US

About us Careers

News & Media Become an Instructor

Reviews Become an A liate

Contact us Become a Partner

Blog Hire from Edureka

Community
DOWNLOAD APP
Sitemap

Blog Sitemap

Community Sitemap

Webinars

CATEGORIES 

CATEGORIES
Cloud Computing DevOps Big Data Data Science BI and Visualization Programming & Frameworks Software Testing

Project Management and Methodologies Robotic Process Automation Frontend Development Data Warehousing and ETL Arti cial Intelligence

Blockchain Databases Cyber Security Mobile Development Operating Systems Architecture & Design Patterns Digital Marketing

TRENDING BLOG ARTICLES 

TRENDING BLOG ARTICLES


Selenium tutorial Selenium interview questions Java tutorial What is HTML Java interview questions PHP tutorial JavaScript interview questions

Spring tutorial PHP interview questions Inheritance in Java Polymorphism in Java Spring interview questions Pointers in C Linux commands

Android tutorial JavaScript tutorial jQuery tutorial SQL interview questions MySQL tutorial Machine learning tutorial Python tutorial

What is machine learning Ethical hacking tutorial SQL injection AWS certi cation career opportunities AWS tutorial What Is cloud computing

What is blockchain Hadoop tutorial What is arti cial intelligence Node Tutorial Collections in Java Exception handling in java

Python Programming Language Python interview questions Multithreading in Java ReactJS Tutorial Data Science vs Big Data vs Data Analyt…

Software Testing Interview Questions R Tutorial Java Programs JavaScript Reserved Words and Keywor… Implement thread.yield() in Java: Exam…

Implement Optical Character Recogniti… All you Need to Know About Implemen…

© 2019 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved. Terms & Conditions    

Legal & Privacy 

https://www.edureka.co/blog/c-sharp-tutorial/ 54/55
2/7/2020 C# Tutorial: The Fundamentals you Need to Master C# | Edureka

"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of
MongoDB, Inc.

https://www.edureka.co/blog/c-sharp-tutorial/ 55/55

You might also like