Vous êtes sur la page 1sur 55

Get Started with C#

Introduction
C# is a simple & powerful object-oriented programming language developed by
Microsoft. C# can be used to create various types of applications, such as web,
windows, console applications or other types of applications using Visual studio.

Dotnet framework:
Version .NET Framework Visual Studio Important Features
C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002
 Basic features

C# 2.0 .NET Framework 2.0 Visual Studio 2005  Generics


 Partial types
 Anonymous methods
 Iterators
 Nullable types
 Private setters (properties)
 Method group conversions (delegates)
 Covariance and Contra-variance
 Static classes

C# 3.0 .NET Framework 3.0\3.5 Visual Studio 2008  Implicitly typed local variables
 Object and collection initializers
 Auto-Implemented properties
 Anonymous types
 Extension methods
 Query expressions
 Lambda expressions
 Expression trees
 Partial Methods

C# 4.0 .NET Framework 4.0 Visual Studio 2010  Dynamic binding (late binding)
 Named and optional arguments
 Generic co- and contravariance
 Embedded interop types

C# 5.0 .NET Framework 4.5 Visual Studio 2012/2013


 Async features
 Caller information

C# 6.0 .NET Framework 4.6 Visual Studio 2013/2015


 Expression Bodied Methods
 Auto-property initializer
 nameof Expression
 Primary constructor
 Await in catch block
Version .NET Framework Visual Studio Important Features
 Exception Filter
 String Interpolation

C# 7.0 .NET Core Visual Studio 2017  out variables


 Tuples
 Discards
 Pattern Matching
 Local functions
 Generalized async return types
 throw Expressions

Dotnet Core

Is a free and open-source web framework, and higher performance than


ASP.NET,[3] developed by Microsoft and the community. It is a modular framework
that runs on both the full .NET Framework, on Windows, and the cross-platform
.NET Core.

Version Release End of


Development Tool
Number Date Support

1.0 2016-06-27 2019-06-27 Visual Studio 2015, 2017

1.1 2016-11-18 2019-06-27 Visual Studio 2015, 2017

2.0 2017-08-14 2018-10-01 Visual Studio 2017

2.1 Long-term
2018-05-30 2021-08-21 Visual Studio 2017
support

Visual Studio 2017 15.9 and 2019


2.2 2018-12-04
16.0 preview 1
in
3.0 Visual Studio 2017 and 2019
development

How to setup environment:


Integrated Development Environment (IDE)
Step1:

Click on https://visualstudio.microsoft.com/

Step2: Select Community 2019, and you will find setup file in the downloads
Step3: You can use it to customize your installation by selecting the feature sets—or
workloads—that you want. Here's how. And click on install/modify.

After the new workloads and components are installed, choose Launch.

For more options:

https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2019

How to create project?


Project is a collection of all supporting files and configurations.

Step1: Open visual studio from start.


Step2: Click on File->New->Project

Step3: select the project and click on next.

Step4:

 Give name for project as “Helloworld”


 Choose the location where you want to store the project.
Step5: The landing page
Advantages of visual studio.
 Easy to create, edit and navigate different files or applications.
 Visual studio includes an excellent debugger that allows you to debug code easily.
Step through the application code to understand it line by line, or identify problems
in your code.
 Intelligence support for .Net Framework classes or custom classes.
 Nuget support for installing third party API/plug-ins in an application.
 Supports integration with many other third-party productive utilities which
enhance the development quality and speed.
 Easy to configure, build and publish .NET applications.
 Provides ALM (Application Life-cycle Management) support for different phases of
the development.

C# Keywords
C# contains reserved words, that have special meaning for the compiler.
These reserved words are called "keywords". Keywords cannot be used as a
name (identifier) of a variable, class, interface, etc.

Keywords in C# are distributed under the following categories:

Modifier Keywords
Modifier keywords are certain keywords that indicate who can modify types
and type members. Modifiers allow or prevent certain parts of programs from
being modified by other parts.

Modifier keywords

Abstract

Async

Const

event

extern

new

override

partial

readonly
Modifier keywords

sealed

static

unsafe

virtual

volatile

Access Modifier Keywords:


Access modifiers are applied on the declaration of the class, method,
properties, fields and other members. They define the accessibility of the class
and its members.

Access Modifiers Usage

public The Public modifier allows any part of the program in the same assembly or another assembly to
access the type and its members.

private The Private modifier restricts other parts of the program from accessing the type and its members.
Only code in the same class or struct can access it.

internal The Internal modifier allows other program code in the same assembly to access the type or its
members. This is default access modifiers if no modifier is specified.

protected The Protected modifier allows codes in the same class or a class that derives from that class to access
the type or its members.

Statement Keywords
Statement keywords are related to program flow.

Statement Keywords

if

else

switch

case

do

for
Statement Keywords

foreach

in

while

break

continue

default

goto

return

yield

throw

try

catch

finally

checked

unchecked

fixed

lock

Method Parameter Keywords


These keywords are applied on the parameters of a method.

Method Parameter Keywords

params

ref

out

Namespace Keywords
These keywords are applied with namespace and related operators.
Namespace Keywords

using

. operator

:: operator

extern alias

Operator Keywords
Operator keywords perform miscellaneous actions.

Operator Keywords

as

await

is

new

sizeof

typeof

stackalloc

checked

unchecked

Access Keywords
Access keywords are used to access the containing class or the base class of
an object or class.

Access keywords

base

this

Literal Keywords
Literal keywords apply to the current instance or value of an object.
Literal Keywords

null

false

true

value

void

Type Keywords
Type keywords are used for data types.

Type keywords

bool

byte

char

class

decimal

double

enum

float

int

long

sbyte

short

string

struct

uint

ulong

ushort
Contextual Keywords
Contextual keywords are considered as keywords, only if used in certain
contexts. They are not reserved and so can be used as names or identifiers.

Contextual Keywords

add

var

dynamic

global

set

value

Contextual keywords are not converted into blue color (default color for
keywords in visual studio) when used as an identifier in Visual Studio. For
example, var in the below figure is not in blue color whereas color of this is
blue color. So var is a contextual keyword.

C# Keywords

Query Keywords
Query keywords are contextual keywords used in LINQ queries.

Query Keywords

from

where

select

group

into

orderby
Query Keywords

join

let

in

on

equals

by

ascending

descending

How to run the Project?

Multiple ways to run the project.

1.Press F5

2.Click on debugger.

How to debug the application?


1.Click on left most of the statement where you want to debug as shown

Or
Click on F9 at the statement.

Or

Variable
The variable in C# is nothing but a name given to a data value.

Value can be stored in system memory.

Syntax:iable Syntax:

<data type> <variable name>;

<datatype> <variable name> = <value>;


Example:
string message;

// value can be assigned after it declared


message = "Hello World!!";
How to declare multiple values?

int i, j, k, l = 0;

int amount, num;

How to assign values?


int i = 1;

int j = i;

Data Types

It holds what kind of data to be stored in system memory.

Reserved .NET Size


Word Type Type (bits) Range (values)
byte Byte Unsigned integer 8 0 to 255
sbyte SByte Signed integer 8 -128 to 127
short Int16 Signed integer 16 -32,768 to 32,767
ushort UInt16 Unsigned integer 16 0 to 65,535
int Int32 Signed integer 32 -2,147,483,648 to 2,147,483,647
uint UInt32 Unsigned integer 32 0 to 4294967295
long Int64 Signed integer 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong UInt64 Unsigned integer 64 0 to 18,446,744,073,709,551,615
float Single Single-precision floating point 32 -3.402823e38 to 3.402823e38
type
double Double Double-precision floating point 64 -1.79769313486232e308 to
type 1.79769313486232e308
decimal Decimal Precise fractional or integral 128 (+ or -)1.0 x 10e-28 to 7.9 x 10e28
type that can represent
decimal numbers with 29
significant digits
char Char A single Unicode character 16 Unicode symbols used in text
bool Boolean Logical Boolean type 8 True or False
object Object Base type of all other types
string String A sequence of characters
DateTime DateTime Represents date and time 0:00:00am 1/1/01 to 11:59:59pm
12/31/9999
Value Type &Reference Type
Value Type:
A data type is a value type if it holds a data value within its own memory space. It
means variables of these data types directly contain their values.

Example: bool

Byte,char,decimal,double,enum,float,int,long,sbyte,short,struct,uint,ulong,ushort.

Reference Type:

Unlike value types, a reference type doesn't store its value directly. Instead, it
stores the address where the value is being stored. In other words, a reference
type contains a pointer to another memory location that holds the data.

The following data types are of reference type:

String, All arrays, even if their elements are value types, Class, Delegates.
Operators

Operator in C# is a special symbol that specifies which operations to perform on


operands. For example, in mathematics the plus symbol (+) signifies the sum of
the left and right numbers. In the same way, C# has many operators that have
different meanings based on the data types of the operands. C# operators usually
have one or two operands. Operators that have one operand are called Unary
operators.

Operator category Operators


Primary x.y
Unary +x
Multiplicative x*y
Additive x+y
Shift x << y
Relational and type testing x<y
Equality x == y
Logical AND x&y
Logical XOR x^y
Logical OR x|y
Conditional AND x && y
Conditional OR x || y
Null-coalescing x ?? y
Conditional ?:
Assignment and lambda expression x=y

Conditional statements
if Statement
C# provides many decision making statements that help the flow of the C#
program based on certain logical conditions. C# includes the following decision
making statements.

1. if statement
2. if-else statement
3. switch statement
4. Ternary operator :?
Here, you will learn about the if statements.

Syntax:
if(boolean expression)
{
// execute this code block if expression evalutes to true
}
The if statement contains boolean expression inside brackets followed by a
single or multi line code block. At runtime, if a boolean expression is evalutes
to true then the code block will be executed.

Consider the following example where the if condition contains true as an


expression.

Example: if condition
if(true)
{
Console.WriteLine("This will be displayed.");
}

if(false)
{
Console.WriteLine("This will not be displayed.");
}
As mentioned above, if statement can contain boolean expression. An
expression which returns either true or false. Following example uses logical
expression as a condition:

Example: if condition
int i = 10, j = 20;

if (i > j)
{
Console.WriteLine("i is greater than j");
}

if (i < j)
{
Console.WriteLine("i is less than j");
}

if (i == j)
{
Console.WriteLine("i is equal to j");
}
In the above example, the boolen expression i < j in the second 'if' statement
evalutes to be true, only the second 'if' statement's code block will be
executed. The first and third 'if' condition evalutes to false, so their code blocks
will not be executed.

if-else Statement
C# also provides for a second part to the if statement, that is else . The else
statement must follow if or else if statement. Also, else statement can appear
only one time in a if-else statement chain.

Syntax:
if(boolean expression)
{
// execute this code block if expression evalutes to true
}
else
{
// always execute this code block when above if expression is false
}
As you can see in the above syntax, the else stament cannot contain any
expression. The code block that follows else statement will always be
executed, when the 'if' condition evalutes to be false.

Example: if else
int i = 10, j = 20;

if (i > j)
{
Console.WriteLine("i is greater than j");
}
else
{
Console.WriteLine("i is either equal to or less than j");
}

else if Statement
The 'if' statement can also follow an 'else' statement, if you want to check for
another condition in the else part.

Example: else if
static void Main(string[] args)
{
int i = 10, j = 20;

if (i > j)
{
Console.WriteLine("i is greater than j");
}
else if (i < j)
{
Console.WriteLine("i is less than j");
}
else
{
Console.WriteLine("i is equal to j");
}
}

You can use multiple else-if statements in a single 'if' statment chain. Also,
you can remove the curly brackets, when the 'if' block has only one line to
execute:

C#- if..else condition:


int i = 10, j = 20;

if (i > j)
Console.WriteLine("i is greater than j");
else if (i < j)
Console.WriteLine("i is less than j");
else if (i == j)
Console.WriteLine("i is equal to j");

Nested if Statements
C# alows nested if else statements. The nested 'if' statement makes the code
more readable.

Example: Nested if statements


int i = 10;

if (i > 0)
{
if (i <= 100)
{
Console.WriteLine("i is positive number less than 100");
}
else
{
Console.WriteLine("i is positive number greater than 100");
}
}

C# - Ternary operator ?:
C# includes a special type of decision making operator '?:' called the ternary
operator.

Variable Syntax:
Boolean Expression ? First Statement : Second Statement
As you can see in the above syntax, ternary operator includes three parts.
First part (before ?) includes conditional expression that returns boolean value
true or false. Second part (after ? and before :) contains a statement which
will be returned if the conditional expression in the first part evalutes to true.
The third part includes another statement which will be returned if the
conditional expression returns false.

Ternary operator returns a value or expression included in the second or third part
of it. It does not execute the statements.

Consider the following example where conditional expression x > y returns


true and so it executes the first statement after ? .

Example: Ternary operator


int x = 20, y = 10;

var result = x > y ? "x is greater than y" : "x is less than or equal to y";

Console.WriteLine(result);

The ternary operator can return a value of any data type. So it is advisable to
store it in implicitly typed variable - var.

For example, it can return an integer value as shown below.

Example: Ternary operator


int x = 20, y = 10;

var result = x > y ? x : y;

Console.WriteLine(result);
Ternary operator can also be used instead of if-else statement. The above
example can be written using if-else statement as shown below.

Example: Ternary operator replaces if statement


int x = 20, y = 10;
int result = 0;

if (x > y)
result = x;
else if (x < y)
result = y;

Console.WriteLine(result);

Nested Ternary operator:


Nested ternary operators are possible by including conditional expression as
a second (after ?) or third part (after :) of the ternary operator..Consider the
following example.

Example: Nested ternary operator


int x = 2, y = 10;

string result = x > y ? "x is greater than y" : x < y ?


"x is less than y" : x == y ?
"x is equal to y" : "No result";
The ternary operator is right-associative. The expression a ? b : c ? d : e is
evaluated as a ? b : (c ? d : e) , not as (a ? b : c) ? d : e .

C# - switch
C# includes another decision making statement called switch. The switch
statement executes the code block depending upon the resulted value of an
expression.

Syntax:
switch(expression)
{
case <value1>
// code block
break;
case <value2>
// code block
break;
case <valueN>
// code block
break;
default
// code block
break;
}
As per the syntax above, switch statement contains an expression into
brackets. It also includes multiple case labels, where each case represents a
particular literal value. The switch cases are seperated by a break keyword
which stops the execution of a particular case. Also, the switch can include a
default case to execute if no case value satisfies the expression.

Case label in switch must be unique. It can be bool, char, string, integer, enum, or
corresponding nullable type.

Consider the following example of a simple switch statement.

Example: switch
int x = 10;

switch (x)
{
case 5:
Console.WriteLine("Value of x is 5");
break;
case 10:
Console.WriteLine("Value of x is 10");
break;
case 15:
Console.WriteLine("Value of x is 15");
break;
default:
Console.WriteLine("Unknown value");
break;
}

The switch statement can include expression or variable of any data type such
as string, bool, int, enum, char etc.

Example: switch statement


string statementType = "switch";

switch (statementType)
{
case "if.else":
Console.WriteLine("if...else statement");
break;
case "ternary":
Console.WriteLine("Ternary operator");
break;
case "switch":
Console.WriteLine("switch statement");
break;
}

Goto in switch:
The switch case can use goto to jump over a different case.

Example: goto in switch case


string statementType = "switch";

switch (statementType)
{
case "DecisionMaking":
Console.Write(" is a decision making statement.");
break;
case "if.else":
Console.Write("if-else");
break;
case "ternary":
Console.Write("Ternary operator");
break;
case "switch":
Console.Write("switch statement");
goto case "DecisionMaking";
}

Nested switch:
Nested switch statments are allowed in C# by writing inner switch statement
inside a outer switch case.

Example: Nested switch statements


int j = 5;

switch (j)
{
case 5:
Console.WriteLine(5);
switch (j - 1)
{
case 4:
Console.WriteLine(4);
switch (j - 2)
{
case 3:
Console.WriteLine(3);
break;
}
break;
}
break;
case 10:
Console.WriteLine(10);
break;
case 15:
Console.WriteLine(15);
break;
default:
Console.WriteLine(100);
break;
}

C# - for loop
The for keyword indicates a loop in C#. The for loop executes a block of
statements repeatedly until the specified condition returns false.

Syntax:
for (variable initialization; condition; steps)
{
//execute this code block as long as condition is satisfied
}
As per the syntax above, the for loop contains three parts: initialization,
conditional expression and steps, which are separated by a semicolon.

1. variable initialization: Declare & initialize a variable here which will be used in
conditional expression and steps part.
2. condition: The condition is a boolean expression which will return either true
or false.
3. steps: The steps defines the incremental or decremental part

Consider the following example of a simple for loop.

Example: for loop


for (int i = 0; i < 10; i++)
{
Console.WriteLine("Value of i: {0}", i);
}
The below figure illustrates the execution steps of above example.
for loop execution steps

As you can see in the above example, first step is to declare & initialize an int
type variable. The second step is to check the condition. The third step is to
execute the code block if the 'if' condition returns true. The fourth step is to
increment the int variable and last step is to eveluate the condition again and
repeat the steps.

It is not necessary to put the initialization, condition and steps into brackets.
You can initialize a variable before the 'for' loop, and the condition and steps
can be defined inside the for loop.

Example: for loop C#


int i = 0;

for(;;)
{
if (i < 10)
{
Console.WriteLine("Value of i: {0}", i);
i++;
}
else
break;
}

Infinite for Loop


Be careful with infinite loop. It will be an infinite loop if for loop does not
contain initialization, condition or steps part. Also, make sure that conditional
expression will return false at some point of time to stop the looping.

Example: Infinite loop


for ( ; ; )
{
Console.Write(1);
}
The control variable for the for loop can be of any numeric data type, such as
double, decimal, etc.

Example: for loop


for (double d = 1.01D; d < 1.10; d+= 0.01D)
{
Console.WriteLine("Value of i: {0}", d);
}

The steps part in a for loop can either increase or decrease the value of a
variable.

Example: for loop


for(int i = 10; i> 0;i--)
{
Console.WriteLine("Value of i: {0}", i);
}

break in for loop


You can also exit from a for loop by using the break keyword.

Example: break in for loop


for (int i = 0; i < 10; i++)
{
if( i == 5 )
break;

Console.WriteLine("Value of i: {0}", i);


}

Nested for Loop


C# allows a for loop inside another for loop.

Example: Nested for loop


for (int i = 0; i < 10; i++)
{
for(int j =i; j< 10; j++)
Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}
C# - while loop:
C# includes the while loop to execute a block of code repeatedly.

Syntax:
While(boolean expression)
{
//execute code as long as condition returns true

}
As per the while loop syntax, the while loop includes a boolean expression as
a condition which will return true or false. It executes the code block, as long
as the specified conditional expression returns true. Here, the initialization
should be done before the loop starts and increment or decrement steps
should be inside the loop.

Example: while loop in C#


int i = 0;

while (i < 10)


{
Console.WriteLine("Value of i: {0}", i);

i++;
}
In the above example, while loop inclues an expression i < 10 . Inside while
loop, value of i increased to 1 (using i++ ). So, the above while loop will be
executed till the value of i will be 10.

Use the break keyword to exit from a while loop as shown below.

Example: break in while loop


int i = 0;

while (true)
{
Console.WriteLine("Value of i: {0}", i);

i++;

if (i > 10)
break;
}
Nested while loop:
Nested while loop is allowed in C#

Example: Nested while loop


int i = 0;

while (i < 2)
{
Console.WriteLine("Value of i: {0}", i);
int j = 1;

i++;

while (j < 2)
{
Console.WriteLine("Value of j: {0}", j);
j++;
}
}

C# - do while
The do-while loop is the same as a 'while' loop except that the block of code
will be executed at least once, because it first executes the block of code and
then it checks the condition.

Syntax:
do
{
//execute code block

} while(boolean expression);
As per the syntax above, do-while loop starts with the 'do' keyword followed
by a code block and boolean expression with 'while'.

Example: do while loop


int i = 0;

do
{
Console.WriteLine("Value of i: {0}", i);

i++;

} while (i < 10);


Just as in the case of the for and while loops, you can break out of the do-
while loop using the break keyword.

Example: break inside do-while


int i = 0;

do
{
Console.WriteLine("Value of i: {0}", i);

i++;

if (i > 5)
break;

} while (true);

Nested do-while
The do-while loop can be used inside another do-while loop.

Example: Nested do while loop


int i = 0;

do
{
Console.WriteLine("Value of i: {0}", i);
int j = i;

i++;

do
{
Console.WriteLine("Value of j: {0}", j);
j++;

} while (j < 2);

} while (i < 2);


C# - Array
We have learned that a variable can hold only one literal value, for
example int x = 1; . Only one literal value can be assigned to a variable x.
Suppose, you want to store 100 different values then it will be cumbersome
to create 100 different variables. To overcome this problem, C# introduced an
array.

An array is a special type of data type which can store fixed number of values
sequentially using special syntax.

The following image shows how an array stores values sequentially.

Array Representation

As you can see in the above figure, index is a number starting from 0, which
stores the value. You can store a fixed number of values in an array. Array
index will be increased by 1 sequentially till the maximum specified array size.

Array in C# is a reference type which is derived from System.Array class.


Array values (elements) are stored sequentially in the memory and that's why
it performs faster.

Array Declaration
An array can be declare using a type name followed by square brackets [].

Example: Array declaration in C#


int[] intArray; // can store int values

bool[] boolArray; // can store boolean values

string[] stringArray; // can store string values

double[] doubleArray; // can store double values

byte[] byteArray; // can store byte values

Student[] customClassArray; // can store instances of Student class


Array Initialization
An array can be declared and initialized at the same time using the new
keyword. The following example shows the way of initializing an array.

Example: Array Declaration & Initialization


// defining array with size 5. add values later on
int[] intArray1 = new int[5];

// defining array with size 5 and adding values at the same time
int[] intArray2 = new int[5]{1, 2, 3, 4, 5};

// defining array with 5 elements which indicates the size of an array


int[] intArray3 = {1, 2, 3, 4, 5};

In the above example, the first statement declares & initializes int type array
that can store five int values. The size of the array is specified in square
brackets. The second statement, does the same thing, but it also assignes
values to each indexes in curley brackets { }. The third statement directly
initializes an int array with the values without giving any size. Here, size of an
array will automatically be number of values.

Initialization without giving size is NOT valid. For example, the following
example would give compile time error.

Example: Invalid Initializing an Array


int[] intArray = new int[]; // compiler error: must give size of an array

Late Initialization
Arrays can be initialized after declaration. It is not necessary to declare and
initialize at the same time using new keyword. Consider the following example.

Example: Late Initialization


string[] strArray1, strArray2;

strArray1 = new string[5]{ "1st Element",


"2nd Element",
"3rd Element",
"4th Element",
"5th Element"
};

strArray2 = new string[]{ "1st Element",


"2nd Element",
"3rd Element",
"4th Element",
"5th Element"
};
However, in the case of late initialization, it must be initialized with the new
keyword as above. It cannot be initialize by only assigning values to the array.

The following initialization is NOT valid:

Example: Invalid Array Initializing


string[] strArray;

strArray = {"1st Element","2nd Element","3rd Element","4th Element" };

Accessing Array Elements


As shown above, values can be assigned to an array at the time of
initialization. However, value can also be assigned to individual index
randomly as shown below.

Example: Setting Values


int[] intArray = new int[5];

intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;

In the same way, you can retrieve values at a particular index, as below:

Example: Accessing Array Elements


intArray[0]; //returns 10

intArray[2]; //returns 30
Use a for loop to access the values from all the indexes of an array by using
length property of an array.

Example: Accessing Array Elements using for Loop


int[] intArray = new int[3]{10, 20, 30 };

for(int i = 0; i < intArray.Length; i++)


Console.WriteLine(intArray[i]);
Use foreach loop to iterate an array.

Example: Accessing Array Elements using foreach Loop


int[] intArray = new int[3]{ 10, 20, 30};

foreach(var i in intArray)
Console.WriteLine(i);

Array Properties and Methods


Method Name Description

GetLength(int dimension) Returns the number of elements in the specified dimension.

GetLowerBound(int dimension) Returns the lowest index of the specified dimension.

GetUpperBound(int dimension) Returns the highest index of the specified dimension.

GetValue(int index) Returns the value at the specified index.

Property Description

Length Returns the total number of elements in the array.

Array Helper Class


.NET provides an abstract class, Array, as a base class for all arrays. It
provides static methods for creating, manipulating, searching, and sorting
arrays.

For example, use the Array.Sort() method to sort the values:

Example: Array Helper Class


int[] intArr = new int[5]{ 2, 4, 1, 3, 5};

Array.Sort(intArr);

Array.Reverse(intArr);

You can create an instance of an Array that starts with index 1 (not default
starting index 0) using Array class as shown below:

Example: Array Helper Class


Array array = Array.CreateInstance(typeof(int),new int[1]{5},new int[1]{1});

array.SetValue(1, 1);
array.SetValue(2, 2);
array.SetValue(3, 3);
array.SetValue(4, 4);
array.SetValue(5, 5);

for (int i = 1; i <= array.Length; i++)


Console.WriteLine("Array value {0} at position {1}", array.GetValue(i), i);

C# Collection:
We have learned about an array in the previous section. C# also includes
specialized classes that hold many values or objects in a specific series, that
are called 'collection'.

There are two types of collections available in C#: non-generic collections


and generic collections. We will learn about non-generic collections in this
section.

The System.Collections namespace includes the interfaces and classes for the
non-generic collections.

C# Collections

As you can see in the above diagram, IEnumerator, IEnumerable, and


ICollection are the top level interfaces for all the collections in C#.

IEnumerator: The IEnumerator interface supports a simple iteration over a


non-generic collection. It includes methods and property which can be
implemented to support easy iteration using foreach loop.

IEnumerable: The IEnumerable interface includes GetEnumerator() method


which returns an object of IEnumerator.

So, all the built-in collection classes and custom collection classes must
implement IEnumerator and IEnumerable interfaces for easy iteration using
foreach loop.

ICollection: The ICollection interface is the base interface for all the collections
that defines sizes, enumerators, and synchronization methods for all non-
generic collections. The Queue and Stack collection implement ICollection
inferface.

IList: The IList interface includes properties and methods to add, insert,
remove elements in the collection and also individual element can be accessed
by index. The ArrayList and BitArray collections implement IList interface.
IDictionary: The IDictionary interface represents a non-generic collection of
key/value pairs. The Hashtable and SortedList implement IDictionary interface
and so they store key/value pairs.

As you can see from the diagram, ArrayList, BitArray, Hashtable, SortedList,
Queue, and Stack collections implement different interfaces and so, they are
used for the different purposes.

Non-generic
Collections Usage

ArrayList ArrayList stores objects of any type like an array. However, there is no need to specify the size of the
ArrayList like with an array as it grows automatically.

SortedList SortedList stores key and value pairs. It automatically arranges elements in ascending order of key by
default. C# includes both, generic and non-generic SortedList collection.

Stack Stack stores the values in LIFO style (Last In First Out). It provides a Push() method to add a value and Pop()
& Peek() methods to retrieve values. C# includes both, generic and non-generic Stack.

Queue Queue stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It
provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection.
C# includes generic and non-generic Queue.

Hashtable Hashtable stores key and value pairs. It retrieves the values by comparing the hash value of the keys.

BitArray BitArray manages a compact array of bit values, which are represented as Booleans, where true indicates
that the bit is on (1) and false indicates the bit is off (0).

C# - ArrayList
ArrayList is a non-generic type of collection in C#. It can contain elements of
any data types. It is similar to an array, except that it grows automatically as
you add items in it. Unlike an array, you don't need to specify the size of
ArrayList.

The following diagram illustrates the ArrayList class hierarchy.


C# ArrayList
As you can see from the above diagram, the ArrayList class
implements IEnumerable , ICollection , and IList interfaces. So, you can create
an object of ArrayList class and assign it to the variable of any base interface
type. However, if you assign it to IEnumerable or ICollection type variable then
you won't be able to add elements and access ArrayList by index.

Example: Create ArrayList


ArrayList myArryList1 = new ArrayList();// Recommended
// or - with some limitations
IList myArryList2 = new ArrayList();
// or - with some limitations
ICollection myArryList3 = new ArrayList();
// or - with some limitations
IEnumerable myArryList4 = new ArrayList();
It is recommended to use ArrayList type of variable for ArrayList object
because ArrayList class contains some additional methods which are not the
members of IListinterface such as AddRange() , BinarySearch() , Repeat() , Reverse() ,
etc.

Important Properties and Methods of ArrayList


Properties Description

Capacity Gets or sets the number of elements that the ArrayList can contain.

Count Gets the number of elements actually contained in the ArrayList.

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a value indicating whether the ArrayList is read-only.

Item Gets or sets the element at the specified index.

Methods Description

Add()/AddRange() Add() method adds single elements at the end of ArrayList.


AddRange() method adds all the elements from the specified collection into ArrayList.

Insert()/InsertRange() Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() method insert all the elements of the specified collection starting from specified
index in ArrayList.

Remove()/RemoveRange() Remove() method removes the specified element from the ArrayList.
RemoveRange() method removes a range of elements from the ArrayList.

RemoveAt() Removes the element at the specified index from the ArrayList.

Sort() Sorts entire elements of the ArrayList.


Methods Description

Reverse() Reverses the order of the elements in the entire ArrayList.

Contains Checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise
false.

Clear Removes all the elements in ArrayList.

CopyTo Copies all the elements or range of elements to compitible Array.

GetRange Returns specified number of elements from specified index from ArrayList.

IndexOf Search specified element and returns zero based index if found. Returns -1 if element not found.

ToArray Returns compitible array from an ArrayList.

Adding Elements into ArrayList

Use the Add()method to add a single element or the AddRange() method to


add multiple elements from the other collections into an ArrayList. Here, the
element means the literal value of a primitive or non-primitive type. Please
note that the AddRange() method only available in the ArrayList class but not
in IList . So, it can only be use with the variable of type ArrayList.

Signature: int Add(Object value)


void AddRange(ICollection c)

Example: Adding Elements into ArrayList


ArrayList arryList1 = new ArrayList();
arryList1.Add(1);
arryList1.Add("Two");
arryList1.Add(3);
arryList1.Add(4.5);

IList arryList2 = new ArrayList()


{
100, 200
};

//Adding entire collection using ArrayList.AdRange() method.


////Note: IList does not contain AddRange() method.
arryList1.AddRange(arryList2);
You can also add items when you initialize it using object initializer syntax.

IList arrayList = new ArrayList() { 100, "Two", 12.5, 200 };


ArrayList can contain multiple null and duplicate values.
Accessing Elements
ArrayList elements can be accessed using indexer, in the same way as an
array. However, you need to cast it to the appropriate type or use the implicit
type varkeyword while accessing it.

Example: Accessing Elements


ArrayList myArryList = new ArrayList();
myArryList.Add(1);
myArryList.Add("Two");
myArryList.Add(3);
myArryList.Add(4.5f);

//Access individual item using indexer


int firstElement = (int) myArryList[0]; //returns 1
string secondElement = (string) myArryList[1]; //returns "Two"
int thirdElement = (int) myArryList[2]; //returns 3
float fourthElement = (float) myArryList[3]; //returns 4.5

//use var keyword


var firstElement = myArryList[0]; //returns 1
Use a foreach or a for loop to iterate an ArrayList.

Example: Iterate ArrayList


IList myArryList = new ArrayList()
{
1,
"Two",
3,
4.5F
};

foreach (var val in myArryList)


Console.WriteLine(val);

//Or
for(int i = 0 ; i< myArryList.Count; i++)
Console.WriteLine(myArryList[i]);

Inserting Elements into ArrayList


Use the IList.Insert() method to insert a single item at the specified index.

Signature: void Insert(int index, Object value)

Example: Insert()
IList myArryList = new ArrayList();
myArryList.Add(1);
myArryList.Add("Two");
myArryList.Add(3);
myArryList.Add(4.5);

myArryList.Insert(1, "Second Item");


myArryList.Insert(2, 100);

foreach (var val in myArryList)


Console.WriteLine(val);

Use the ArrayList.InsertRange() method to insert all the values from another
collection into ArrayList at the specfied index. Please note that
the InsertRange() method only available in the ArrayList class but not in IList .
So, it can only be use with the variable of type ArrayList.

Signature: Void InsertRange(int index, ICollection c)

Example: InsertRange()
IList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);

ArrayList arryList2 = new ArrayList();


arryList2.Add(10);
arryList2.Add(20);
arryList2.Add(30);

arryList2.InsertRange(2, arryList1);

foreach(var item in arryList2)


Console.WriteLine(item);

Remove Elements from ArrayList


Use the IList.Remove() method to remove a specified element from an
ArrayList.

Signature: void Remove(Object obj)

Example: Remove()
IList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);
arryList1.Add(300);

arryList1.Remove(100); //Removes 1 from ArrayList

foreach (var item in arryList1)


Console.WriteLine(item);

Use the IList.RemoveAt() method to remove an element from the specified index
location.

Signature: void RemoveAt(int index)

Example: RemoveAt()
IList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);
arryList1.Add(300);

arryList1.RemoveAt(1); //Removes the first element from an ArrayList

foreach (var item in arryList1)


Console.WriteLine(item);

Use the ArrayList.RemoveRange() method to remove multiple elements from the


specified index till the specified number of elements in the ArrayList. Please
note that the RemoveRange() method only available in the ArrayList class but not
in IList . So, it can only be use with the variable of type ArrayList.

Signature: void RemoveRange(int index, int count)

Example: RemoveRange()
ArrayList arryList1 = new ArrayList();
arryList1.Add(100);
arryList1.Add(200);
arryList1.Add(300);

arryList1.RemoveRange(0,2);//Removes two elements starting from 1st item (0 index)

foreach(var item in arryList1)


Console.WriteLine(item);

ArrayList Sorting
The ArrayList class includes Sort() and Reverse() method. The Sort() method
arranges elements in ascending order. However, all the elements should have
same data type so that it can compare with default comparer otherwise it will
throw runtime exception.
The Reverse() method arranges elements in reverse order. Last element at zero
index and so on.

Example: Sort(), Reverse()


ArrayList arryList1 = new ArrayList();
arryList1.Add(300);
arryList1.Add(200);
arryList1.Add(100);
arryList1.Add(500);
arryList1.Add(400);

Console.WriteLine("Original Order:");

foreach(var item in arryList1)


Console.WriteLine(item);

arryList1.Reverse();
Console.WriteLine("Reverse Order:");

foreach(var item in arryList1)


Console.WriteLine(item);

arryList1.Sort();
Console.WriteLine("Ascending Order:");

foreach(var item in arryList1)


Console.WriteLine(item);

Check for an Existing Elements in ArrayList


The IList.Contains() method checks whether specified element exists in the
ArrayList or not. Returns true if exists otherwise false.

Example: Contains()
IList myArryList = new ArrayList();
myArryList.Add(100);
myArryList.Add("Hello World");
myArryList.Add(300);

Console.WriteLine(myArryList.Contains(100)); // true

C# - Hashtable
C# includes Hashtable collection in System.Collections namespace, which is
similar to generic Dictionary collection. The Hashtable collection stores key-
value pairs. It optimizes lookups by computing the hash code of each key and
stores it in a different bucket internally and then matches the hash code of
the specified key at the time of accessing values.

The following diagram illustrates the Hashtable class hierarchy.

C# Hashtable
Important Propertis and Methods of Hashtable
Property Description

Count Gets the total count of key/value pairs in the Hashtable.

IsReadOnly Gets boolean value indicating whether the Hashtable is read-only.

Item Gets or sets the value associated with the specified key.

Keys Gets an ICollection of keys in the Hashtable.

Values Gets an ICollection of values in the Hashtable.

Methods Usage

Add Adds an item with a key and value into the hashtable.

Remove Removes the item with the specified key from the hashtable.

Clear Removes all the items from the hashtable.

Contains Checks whether the hashtable contains a specific key.

ContainsKey Checks whether the hashtable contains a specific key.

ContainsValue Checks whether the hashtable contains a specific value.

GetHash Returns the hash code for the specified key.

Add key-value into Hashtable


The Add() method adds an item with a key and value into the Hashtable. Key
and value can be of any data type. Key cannot be null whereas value can be
null.

Add() Signature: void Add(object key, object value);

Example: Add()
Hashtable ht = new Hashtable();

ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add(5, null);
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5);
You can also assign key and value at the time of initialization using object
initializer syntax:

Example: Add()
Hashtable ht = new Hashtable()
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, null },
{ "Fv", "Five" },
{ 8.5F, 8.5 }
};
Hashtable can include all the elements of Dictionary as shown below.

Example: Add()
Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "one");
dict.Add(2, "two");
dict.Add(3, "three");

Hashtable ht = new Hashtable(dict);

Note : Add() will throw an exception if you try to add a key that already exists in the
Hashtable. So always check the key using the Contains() or ContainsKey() method
before adding a key-value pair into the Hashtable.

Access Hashtable
You can retrive the value of an existing key from the Hashtable using indexer.
Please note that the hashtable indexer requires a key.

Example: Access Hashtable


Hashtable ht = new Hashtable();

ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
ht.Add(4, "Four");
ht.Add("Fv", "Five");
ht.Add(8.5F, 8.5F);

string strValue1 = (string)ht[2];


string strValue2 = (string)ht["Fv"];
float fValue = (float) ht[8.5F];
Console.WriteLine(strValue1);
Console.WriteLine(strValue2);
Console.WriteLine(fValue);
Note:
Hashtable is a non-generic collection so it can contains a key and a value of any data
type. So values must be cast to an appropriate data type otherwise it will give
compile-time error.

Hashtable elements are key-value pairs stored in DictionaryEntry. So you cast


each element in Hashtable to DictionaryEntry. Use the foreach statement to
iterate the Hashtable, as shown below:

Example: Iterate Hashtable


Hashtable ht = new Hashtable()
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, null },
{ "Fv", "Five" },
{ 8.5F, 8.5 }
};

foreach (DictionaryEntry item in ht)


Console.WriteLine("key:{0}, value:{1}",item.Key, item.Value);

Hashtable has a Keys and a Values property that contain all the keys and
values respectively. You can use these properties to get the keys and values.

Example: Access Hashtable using Keys & Values


Hashtable ht = new Hashtable();
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, null },
{ "Fv", "Five" },
{ 8.5F, 8.5 }
};

foreach (var key in ht.Keys )


Console.WriteLine("Key:{0}, Value:{1}",key , ht[key]);

Console.WriteLine("***All Values***");
foreach (var value in ht.Values)
Console.WriteLine("Value:{0}", value);

Remove elements in Hashtable


The Remove() method removes the item with the specified key from the
hashtable.

Remove() Method Signature: void Remove(object key)

Example: Remove()
Hashtable ht = new Hashtable()
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, null },
{ "Fv", "Five" },
{ 8.5F, 8.5 }
};

ht.Remove("Fv"); // removes {"Fv", "Five"}

Check for Existing Elements


Contains() and ContainsKey() check whether the specified key exists in the
Hashtable collection. ContainsValue() checks whether the specified value
exists in the Hashtable.

Contains(), ContainsKey() and ContainsValue() Signatures:

bool Contains(object key)


bool ContainsKey(object key)
bool ContainsValue(object value)

Example: Contains
Hashtable ht = new Hashtable()
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" }
};

ht.Contains(2);// returns true


ht.ContainsKey(2);// returns true
ht.Contains(5); //returns false
ht.ContainsValue("One"); // returns true
Clear()
Clear() method removes all the key-value pairs in the Hashtable.

Clear() Method Signature: void Clear()

Example: Clear()
Hashtable ht = new Hashtable()
{
{ 1, "One" },
{ 2, "Two" },
{ 3, "Three" },
{ 4, "Four" },
{ 5, null },
{ "Fv", "Five" },
{ 8.5F, 8.5 }
};

ht.Clear(); // removes all elements


Console.WriteLine("Total Elements: {0}", ht.Count);

Generics in C#
Generics allow for designing a classes and methods whose types are specified only at the time of
declaration and instantiation. This enables development of universal classes and methods that help in
improving performance, productivity and type-safety.

Generics introduced in C# 2.0. Generics allow you to define a class with


placeholders for the type of its fields, methods, parameters, etc. Generics
replace these placeholders with some specific type at compile time.

A generic class can be defined using angle brackets <>. For example, the
following is a simple generic class with a generic member variable, generic
method and property.

Example: Generic class


class MyGenericClass<T>
{
private T genericMemberVariable;

public MyGenericClass(T value)


{
genericMemberVariable = value;
}
Example: Generic class
MyGenericClass<string> strGenericClass = new MyGenericClass<string>("Hello Generic
World");

strGenericClass.genericProperty = "This is a generic property example.";


string result = strGenericClass.genericMethod("Generic Parameter");

Generic Class as Base Class


When deriving from a generic base class, you must provide a type argument
instead of the base-class's generic type parameter as shown below.

Example: Generic
class MyDerivedClass : MyGenericClass<string>
{
//implementation
}
If you want the derived class to be generic then no need to specify type for
the generic base class.

Example: Generic derived class


class MyDerivedClass<U> : MyGenericClass<U>
{
//implementation
}
If the generic base class has constraints, the derived class must use the
same constraints.

Example: Constraints
class MyGenericClass<T> where T: class
{
// Implementation
}

class MyDerivedClass<U> : MyGenericClass<U> where U: class


{
//implementation
}

Generic Delegates
As you have already learned in the previous section, the delegate defines the
signature of the method which it can invoke. A generic delegate can be defined
the same way as delegate but with generic type.
For example, consider the following generic delegate that takes two generic
parameters.

Example: Generic Delegate


class Program
{
public delegate T add<T>(T param1, T param2);

static void Main(string[] args)


{
add<int> sum = AddNumber;

Console.WriteLine(sum(10, 20));

add<string> conct = Concate;

Console.WriteLine(conct("Hello","World!!"));
}

public static int AddNumber(int val1, int val2)


{
return val1 + val2;
}

public static string Concate(string str1, string str2)


{
return str1 + str2;
}
}

In the above example, add delegate is generic. In the Main() method, it has
defined add delegate of int type variable sum. So it can point to the
AddNumber() method which has int type parameters. Another variable of add
delegate uses string type, so it can point to the Concate method. In this way,
you can use generic delegates for different methods of different types of
parameters.

Note:
A generic delegate can point to methods with different parameter types. However,
the number of parameters should be the same.

Generics can be applied to the following:

 Interface
 Abstract class
 Class
 Method
 Static method
 Property
 Event
 Delegates
 Operator

Advantages of Generics
1. Increases the reusability of the code.
2. Generic are type safe. You get compile time errors if you try to use a different
type of data than the one specified in the definition.
3. Generic has a performance advantage because it removes the possibilities of
boxing and unboxing.

C#: Constraints in Generics


You have learned abut the generics in the previous section. Generics allow you
to define a class with placeholders for the type of its fields, methods,
parameters, etc. Consider the following example of a generic class.

Example: Generic class


class MyGenericClass<T>
{
private T genericMemberVariable;

public MyGenericClass(T value)


{
genericMemberVariable = value;
}

public T genericMethod(T genericParameter)


{
Console.WriteLine("Parameter type: {0}, value: {1}",
typeof(T).ToString(),genericParameter);
Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(),
genericMemberVariable);

return genericMemberVariable;
}

public T genericProperty { get; set; }


}
In the above example, the generic class MyGenericClass defines a placeholder
for the type, but the placeholder is like a black box, because MyGenericClass
doesn't know anything about the placeholder type, whether it is primitive or
non-primitive type, or an interface or custom class etc.
C# includes Constraints to specify which type of placeholder type with the
generic class is allowed. It will give a compile time error if you try to instantiate
a generic class using a placeholder type that is not allowed by a constraints.
For example, if the generic constraints specifies that only reference type can
be used with the generic class then you cannot use value type to create an
object of generic type.

Constraints can be applied using the where keyword. In the following


example, MyGenericClass specifies the constraints that only a reference type
can be used with MyGenericClass. This means that only a class can be a
placeholder type not the primitive types, struct etc.

Example: Generic Class with Constraints


class MyGenericClass<T> where T: class
{
private T genericMemberVariable;

public MyGenericClass(T value)


{
genericMemberVariable = value;
}

public T genericMethod(T genericParameter)


{
Console.WriteLine("Parameter type: {0}, value: {1}",
typeof(T).ToString(),genericParameter);
Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(),
genericMemberVariable);

return genericMemberVariable;
}

public T genericProperty { get; set; }


}
So now, you cannot use int as a placeholder type. The following would give a
compile time error.

Example: Compile Time Error


MyGenericClass<int> intGenericClass = new MyGenericClass<int>(10);
String or any class type is a valid type because it is a reference type.

Example: Intantiate Constrained Generic Class:


MyGenericClass<string> strGenericClass = new MyGenericClass<string>("Hello World");

MyGenericClass<Student> strGenericClass = new MyGenericClass<Student>(new Student());


The following table lists the types of generic constraints.

Constraint Description

where T : class Type must be reference type.

where T: struct Type must be value type.

where T: new() Type must have public parameterless constructor.

where T: <base class name> Type must be or derive from the specified base class

where T: <interface name> Type must be or implement the specified interface.

where T: U Type supplied for T must be or derive from the argument supplied for U.

Multiple constraints:
A generic class can have multiple constraints as shown below.

Multiple constraints:
class MyGenericClass<T, U> where T: class where U:struct
{
...
}

Constraint on Generic Methods


You can apply constraints on the generic methods also.

Method constraint:
class MyGenericClass<T> where T: class
{
public T genericMethod<U>(T genericParameter, U anotherGenericType) where U: struct
{
Console.WriteLine("Generic Parameter of type {0}, value {1}",
typeof(T).ToString(),genericParameter);
Console.WriteLine("Return value of type {0}, value {1}", typeof(T).ToString(),
genericMemberVariable);

return genericMemberVariable;
}
}
Thus, constraints can be applied on generic types.

C# - enum
In C#, enum is a value type data type. The enum is used to declare a list of
named integer constants. It can be defined using the enum keyword directly
inside a namespace, class, or structure. The enum is used to give a name to
each constant so that the constant integer can be referred using its name.

Example: enum
enum WeekDays
{
Monday = 0,
Tuesday =1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday =5,
Sunday = 6
}

Console.WriteLine(WeekDays.Friday);
Console.WriteLine((int)WeekDays.Friday);
By default, the first member of an enum has the value 0 and the value of each
successive enum member is increased by 1. For example, in the following
enumeration, Monday is 0, Tuesday is 1, Wednesday is 2 and so forth.

Example: enum
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

Console.WriteLine((int)WeekDays.Monday);
Console.WriteLine((int)WeekDays.Friday);

Vous aimerez peut-être aussi