Académique Documents
Professionnel Documents
Culture Documents
What is C#?
Characteristics
Object-oriented.
Primarily imperative or procedural.
Structured (as opposed to monolithic).
Strongly typed.
ISO and ECMA standardized.
Why C#?
The first Component Oriented language in the C/C++ family
C# is pure object-oriented, compared to C++ which is a mixture of object-oriented and procedure-oriented.
Ease-to-development, The rich class library makes many functions easy to be implemented
You need not put much attention on such problems as memory leak, which is troubling problem for C++ programmer
Good support for distributed system
Note: Process of rapidly creating an application using an IDE is called Rapid Application Development (RAD)
Modernized language
Cross-language and Cross-platform capabilities
Versioning to provide ease of administration and deployment.
Migration from C/C++ and Java easily
Interoperate with other languages
XML support for Web-based component interaction
C# also gives you the capability to build durable system-level components by virtue of the following features:
Types of Application
Console
Application
Has standard
streams (out, in, err)
Windows
Application
Service
GUI based
No standard streams
(out, in, err)
No standard streams
(out, in, err)
Main thread is
commandeered by
the SCM
No GUI
IDE
MS Visual Studio
A fully-featured, and extensible IDE for creating modern applications for Windows, Android, and iOS, as well as web applications and
cloud services
Microsoft Integrate Development Environment (IDE)
Create, run, and debug programs
Visual Programming
Create program by dragging and dropping predefined building blocks into place
Languages Supported
C#, Visual Basic, F#, C++, HTML, JavaScript, Python, and more
Microsoft Visual Studio Products
Visual Studio Community (Free for developers - Create multi-platform apps for Windows, iOS, Android)
Visual Studio Professional
Visual Studio Enterprise (Complete Edition)
Visual Studio Code (Code editing for building and debugging modern web and cloud applications
Visual Studio Team Services (Share code, track work, and ship software)
Team Foundation Server
Available in
Chinese, English, French, Portuguese, German, Italian, Japanese, Korean, Spanish and Russian
Note: MSDN stands for Microsoft Developer Network
7
Date
.NET Framework
Visual Studio
C# 1.0
January 2002
C# 1.2
April 2003
C# 2.0
November 2005
C# 3.0
November 2007
C# 4.0
April 2010
.NET Framework 4
C# 5.0
August 2012
C# 6.0
July 2015
Members - 1
Variables
Members in c#, are the members in class that represents
data and behavior of the class. Variable is one such member
in class.
datatype variable_name;
Ex: int i;
i is variable of the type int.
Variable initialization
1. datatype variable_name=value;
Ex: int i=100;
i is variable of the type int and stores value of 100.
2. variable_name=value;
Ex: i=100;
10
Constants
11
Properties
Members - 2
Methods
Method is a group of statements put together to perform a
task.
Syntax
Access_specifier Return_type Method_name(parameterlist)
{
//statements to execute.
}
Access_specifier: determines the visibility of the
method.
Return_type: A method may return value. Return type
is the data type of the value that method returns. If
the method is not returning any value then return
type is void.
Method_name: it is unique identifier.
Parameterlist: it is enclosed in paranthesis, these
values are used to pass and receive data from the
method.
Statement to execute: set of the statements to be
executed to complete the specific tasks.
14
Constructor
Example of constructor
Syntax
Access_specifier constructor_name(parameterlist)
{
//code for initialzation.
}
15
Destructor
Example of Destructor
16
Data type
Data Types in a programming language describes that what type of data a variable can hold.
Since C# is type-safe language, every variable and object must have a declared type.
Each data type needs some specific size of memory to hold that particular data.
There are two types of data types
Value types
Reference types
18
19
20
Operators - 1
Operators
An operator is a symbol that tells the complier to perform specific mathematical or logical manipulation in an expression.
Operators in programming languages are taken from mathematics. These are used to process the data in an expression.
C# provides rich set of built in operators, below are the few operators provided by c#.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Operator Precedence
22
Arithmetic Operators
Below table represents all the arithmetic operators supported in C#. And example respectively.
Consider integer variable A is assigned with value of 60 and integer variable B is assigned with value of 30.
Example represents usage of arithmetic operators. AddNumbers() method is performing addition on operands A and B.
Other operators can be used similarly as in the example to perform various mathematic manipulations.
23
Relational Operators
Below table represents all the relational operators supported in C#. And example respectively.
Consider integer variable A is assigned with value of 10 and integer variable B is assigned with value of 30.
Example represents usage of relational operators. FindLargestNumber() method is used find largest number among operands
A and B.
Other operators can be used similarly as in the example to perform various mathematic manipulations.
24
Logical Operators
Below table represents all the logical operators supported in C#. And example respectively.
Consider Boolean variable A is assigned with value of true "and boolean variable B is assigned with value of false.
Example represents usage of logical operators. VerifyUsernameAndPassword() method is used verify the user credentials.
Other operators can be used similarly as in the example to perform various mathematic manipulations.
25
Operators - 2
Bitwise Operators
Below table represents all the bitwise operators supported in C#. And example respectively.
These operators works on bits and perform bit by bit operation.
Consider int variable A is assigned with value of 60 and int variable B is assigned with value of 13.
27
Assignment Operators
Below table represents all the assignment operators supported in C#. And example respectively.
28
In the example below simple = assign operator is used. It assigns value from right hand side operands to left hand side
operand.
Here value of A+B that is 90 is assigned to variable result.
29
Operator Precedence
Operator precedence defines the grouping of terms in an expression.
Certain operators have higher precedence than others.
For example, the multiplication operator has higher precedence than the addition operator.
x = 10+ 2* 2;
In the expression above 2*2 will be performed 1st as multiplication operator has higher precedence than addition.
The value of 2*2=4 will be added to 10. So the result will be 14.
Below table represents the common C# operators ordered by precedence (highest precedence first):
30
31
if statement
If statement consist of a Boolean value followed by
one or more statements.
Start
Condition
true
false
If block
End
33
If else statement
Start
Condition
true
false
If block
Else block
End
34
Nested If statement
Start
false
Condition
true
true
Condition
false
true
Else Block
If block
End
End
35
Condition
false
true
If block
true
Else if Condition
false
true
If block
Else block
End
37
Switch Statement
Switch statement contains one or more case labels which are
tested against switch condition.
Switch
Condition
Case 1 Block
Case 2 Block
Case 3 Block
Default Block
End
38
39
Ternary Operator
This operator is used to make conditional expression in C#.
Syntax:
Condtion?statement1:expression2;
Example:
40
For loop
Initialization
Example:
Condition
False
Code Block
Increment
End
42
Foreach loop
This iterates over a collection.
This deals with the each element of the collection. It does not iterate with index number.
Syntax:
foreach(datatype item in collection)
{
//statement of code
}
Example:
43
Syntax:
while (condition)
{
// statements of code
}
Example:
Condition
False
Code Block
End
45
Do While loop
For and while check the condition at the beginning of the loop, but it checks the
condition at the end of the loop.
For and while runs the block of code zero or more times but it executes block of code at
least one time.
Code Block
Syntax:
do
{
//statements of code
}
while (condition)
Condition
Example:
False
End
46
47
49
50
private access specifier : Member can only be accessed by code in the same class
51
protected access specifier : Member can only be accessed by code in the same class or in a derived class.
52
internal access specifier : Member can be accessed by any code in the same assembly, but not from another assembly.
53
protected internal access specifier : Member can be accessed by any code in the same assembly, or by any derived class
in another assembly.
54
Types in C# - 1
Class
The class is the fundamental building block of code and it is like blueprint which specifies what a type can do.
It is example for encapsulation in C#
We define class using keyword class
Syntax to define a class
Access_specifier class class_name
56
Example of Class
57
Object
Object creates a memory for the class and allows us to use the members of the class.
Syntax to define a object
Object_type object_name;
58
59
Types in C# - 2
interface
It is same like a class but has no implementation.
61
Example of an Interface
62
Enum
63
Example of an Enumeration
64
Delegates
65
Example of Delegates
66
Arrays
Arrays
Collection of items which are of same data type.
An array index starts at zero.
Declaration of simple array
int[] intArray;
Defining arrays
string[] stringArray = new string[10];
Initializing dynamic array
string[] stringArray = new string[] { India", USA", China", Japan, UK" };
Initializing fixed length array
string[] stringArray = new string[5] { India", USA", China", Japan, UK" };
Accessing arrays
Console.WriteLine(stringArray [0]); Console.WriteLine(stringArray [1]); Console.WriteLine(stringArray [2]);
68
Types of Arrays
There are three types in arrays
Single-dimensional array
Multidimensional array
Jagged array
Single dimensional array:
Single-dimensional arrays are the simplest form of arrays.
Example explained in previous slide is single-dimensional array.
Multidimensional array:
A multi-dimensional array is an array with more than one dimension.
A multi-dimensional array can be fixed-sized or dynamic sized
Declaring a multidimensional array
string[,] mutliDimStringArray
Column 0
Column 1
Row 0
India
Asia
Row 1
China
Asia
Row 2
USA
Initializing multidimensional array
string[,] countryNames = new string[3, 2] { { India", Asia" }, { China", Asia" }, { USA", America" }};
America
Jagged Arrays
Jagged arrays are arrays of arrays.
The elements of a jagged array are other arrays.
Declaring jagged arrays
string[][] stringJaggedArray = new string[3][];
Initializing jagged array
stringJaggedArray [0] = new string [3] {Asia, Africa, America};
stringJaggedArray [1] = new string [5] {India, South Africa, USA, China, Japan};
stringJaggedArray [2] = new string [7] {New Delhi, Johannesburg, Washington, Beijing, Tokyo};
Accessing jagged array
Console.WriteLine(stringJaggedArray [1][0]);
We can also have multidimensional arrays inside an array.
70
Collections
List
List is same as arrays except there is no fixed size for this.
List is a collection of items which are of same data type.
Syntax for defining a List
List<data type> listName;
Initializing List
List<data type> listName = new List<data type>();
Adding items to the List
listName.Add(item);
Accessing List data
Console.WriteLine(listName [0]);
72
ArrayList
ArrayList is same as List except it can hold the items of any data type.
ArrayList is a collection of items which are of same data type or different data type.
An ArrayList index starts at zero.
Syntax for defining a ArrayList
ArrayList arrayListName;
Initializing ArrayList
ArrayList arrayListName = new ArrayList ();
73
Dictionary
Dictionary is same as List, but it holds the items in the form of key value pair.
Dictionary is a collection of items that in the form of key value pair which are of same data type.
Syntax for defining a Dictionary
Dictionary<type_Key, type_value> dictionaryName;
Initializing Dictionary
Dictionary<type_Key, type_value> dictionaryName = new Dictionary<type_Key, type_value>();
Adding items to the Dictionary
dictionaryName.Add(key, value);
Accessing Dictionary data
Console.WriteLine(dictionaryName [0]);
74
HashTable
Hashtable is same as Dictionary, but it can holds the items in the form of key value pair which are of any data type.
Hashtable is a collection of items that in the form of key value pair which are of same data type or different data type.
Syntax for defining a Hashtable
Hashtable hashtableName;
Initializing Hashtable
HashTable hashtableName = new HashTable();
Adding items to the Hashtable
hashtableName.Add(key, value);
Accessing Hashtable data
Console.WriteLine(hashtableName [0]);
75
Operator Keywords 1
Operator Keywords
Used to perform miscellaneous actions such as creating objects, checking the run-time type of an object, obtaining the size of a type,
and other actions.
o
o
o
o
o
as
is
new
sizeof
stackalloc
o
o
o
o
typeof
true
false
await
77
as
as operator casts object to a different type.
It returns null if object was of an incompatible type.
Considers Boxing/Unboxing conversion, reference conversion , but user defined conversion are not considered.
class Base
{
public override string ToString()
{
return "Base Class";
}
}
class Derived : Base { }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
Console.WriteLine(b.ToString());
}
}
78
is
The is keyword compares an object to a type, and if they're the same or of the same "kind" (the object inherits the type), returns true
Using is on a null variable always returns false.
Considers Boxing/Unboxing conversion, reference conversion , but user defined conversion are not considered.
Example:
79
New operator
Used to create objects and invoke constructors
If the new operator fails to allocate memory, it throws the exception, OutOfMemoryException.
Syntax : general form
class-name object-name = new class-name();
Example
80
Operator Keywords 2
sizeof
Used to obtain the size in bytes for an unmanaged type.
Unmanaged type include built-in types, enum type, pointer type, user defined structs.
Expression
sbyte
byte
short
ushort
int
uint
long
ulong
char
value
1
1
2
2
4
4
8
8
2
float
double
decimal
bool
4
8
16
1 82
(Unicode)
typeof
Used to determine the type of the parameter passed to it.
It returns the System. Type object associated with that type
83
True/false operator
The true and false operators can be overloaded, to allow a class to represent its own state as true or false.
returns the bool value true to indicate that an operand is true and returns false otherwise.
84
stackalloc
The stackalloc keyword is used in an unsafe code context to allocate a block of memory on the stack.
Reason to use stackalloc is performance, faster to allocate memory on heap and automatically freed when method exits.
Example
A block of memory of sufficient size to contain 100 elements of type int is allocated on the stack, not the heap
The lifetime of the memory block is limited to the lifetime of the method in which it is defined
85
Stackalloc - Example
static unsafe void Main()
{
const int arraySize = 20;
int* fib = stackalloc int[arraySize];
int* p = fib;
// The sequence begins with 1, 1.
*p++ = *p++ = 1;
for (int i = 2; i < arraySize; ++i, ++p)
{
// Sum the previous two numbers.
*p = p[-1] + p[-2];
}
for (int i = 0; i < arraySize; ++i)
{
Console.WriteLine(fib[i]);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
86
Exception Handling
Exception Handling
The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program
is running.
Exceptions provide a way to transfer control from one part of a program to another.
88
Blocks of Exception
C# exception handling is built upon four keywords
o
try: code that could throw an exception is put in the try block
catch: The catch keyword indicates the catching of an exception. exception handling code goes in this block.
finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
89
Syntax
try
{
// Statement causing exception
}
finally
{
// Statements to be executed
}
90
{
// Error handling code
}
finally
{
// Statements to be executed
}
91
: " + resultVal);
}
catch (Exception ex)
{
Console.WriteLine("Exception catch here - details
}
finally
{
Console.WriteLine("Enter finally block ");
}
: " + ex.ToString());
}
}
Output
92
Exception Classes
The exception classes in C# are derived from the System. Exception class.
System.SystemException : base class for all the predefined system exception like System.IO.IOException,
System.IndexOutOfRangeException, System.DivideByZeroException, System.OutOfMemoryException etc.
The exception object has important properties like Message, StackTree, Targetsite to better understand exception.
94
User-Defined Exceptions
User defined exceptions (also known as Application exception) are explicitly raised by Application on its own condition
Exception
User-Defined Exception
New class
Derived from Exception class
95
class TestTemperature
{
static void PrintTemperature(int iTemperature)
{
if (iTemperature == 0)
throw (new TempIsZeroException("Zero Temperature found"));
else
Console.WriteLine("Temperature: {0}", iTemperature);
}
static void Main(string[] args)
{
try
{
PrintTemperature(0);
}
catch (TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
Output
96
APIs in C# .net
98