0% found this document useful (0 votes)
39 views144 pages

Unit - 1

The document provides an overview of the C# programming language, detailing its features, types, variables, constants, operators, control structures, and type conversion. C# is a modern, object-oriented language developed by Microsoft, emphasizing type safety and encapsulation within classes. It covers various aspects such as value types, reference types, and control structures for managing program flow.

Uploaded by

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

Unit - 1

The document provides an overview of the C# programming language, detailing its features, types, variables, constants, operators, control structures, and type conversion. C# is a modern, object-oriented language developed by Microsoft, emphasizing type safety and encapsulation within classes. It covers various aspects such as value types, reference types, and control structures for managing program flow.

Uploaded by

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

Unit – 2

The C#
Language
Road Map

• Introduction • Classes & Objects • Pass by


Reference
• Features • Encapsulation
• Collections
• Types • Inheritance
• Delegates
• Variables & • Polymorphism
Constants • Events
• Abstract & Sealed
• Operators Classes

• Control Structures • Interface

• Type Conversion • Properties

• Arrays • Indexers

• Pointers • Enumerations
Introductio
n
Introduction

• C# is a modern and high-level object-oriented programming


language developed by Microsoft. It is derived from C++ and
Java.

• C# was developed by Anders Hejlsberg and his team during


the
development of .NET Framework.

• C# is a .NET-compliant language, meaning it follows the


Common
Language Specifications (CLS).

• A C# Source Files is saved with .cs extension. The C#


Compiler converts the C# code into CIL/MSIL which is then
Featur
es
Features

• Simple:

• C# is more readable, understandable compared to


lower-level
languages such as C++.

• Modern:

• C# is used for building scalable, robust and powerful


apps.

• Object-Oriented:

• C# is a Pure Object-Oriented Programming Language.

• C# code is always encapsulated within classes.


Features

• Type Safety:

• C# does not allow unsafe type conversions such storing an


integer in
a character-type variable.
• Variables and objects are always initialized with some
default value.
• Arrays cannot be accessed outside of bounds.
Type
s
Type
s
• Types are used for specifying what type of data will be stored by
variables.

• C# uses the types provided by .NET Framework. Each .NET type


has an
alias in C#.

• There are three categories of types:

• Value Types

• Pointer Types

• Reference Types
Type
s
Types: Value
Types
• Value Type variables directly store the data in
memory.

• All the Value Types are derived from


System.ValueType class.

• There are 4 sub-categories of Value Types:

• Simple Types:

• Stores individual/atomic values

• All Simple Types in .NET are actually


structures.
• Nullable Types:

• Simple Types with the ability of storing null


Types: Value
Types
• Structures:

• A User Defined Type that stores values of


different types.
• Enum:

• A User Defined Type that stores named


constants.
Types: Value
Types
• These are the Simple Types
in .NET:

C# Type (Alias) .NET Type Size (bytes) Range

byte System.Byte 1 0 to 255

sbyte System.SByte 1 -128 to 127

short System.Int16 2 -32,768 to 32,767

ushort System.UInt16 2 0 to 65,535

int System.Int32 4 -2,147,483,648 to


2,147,483,647
uint System.UInt32 4 0 to 4294967295
Types: Value
Types
• These are the Simple Types
in .NET:

C# Type (Alias) .NET Type Size (bytes) Range


-9,223,372,036,854,775,808 to
long System.Int64 8
9,223,372,036,854,775,807
ulong System.UInt64 8 0 to
18,446,744,073,709,551,615
float System.Single 4 -3.4e38 to 3.4e38

double System.Doubl 8 -1.7e308 to 1.7e308


e
decimal System.Decim 16 (+ or -)1.0 x 10e-28 to 7.9 x
al 10e28
char System.Char 2 Unicode symbols used in text

bool System.Boolea 1 true or false


Types: Reference Types

• Reference Types do not store the values directly, instead they


store the reference (memory location) of the value.

• So, a single value can be referred by multiple Reference Type


variables. Changing the value through one variable is also
reflected on other variables.

• There are many reference types already provided in .NET.

C# Type (Alias) .NET Type (Class)

string System.String

object System.Object
Types: Reference Types

• Reference Types:

• string type:

• string type is used for storing


strings.
• It is an alias for System.String
class.
• It is derived from
System.Object class.
Types: Reference Types

• Reference Types:

• object type:

• object type is the ultimate parent of all .NET Types


(Value or
Reference Types)
• It is an alias for the System.Object class.

• Any type can be converted to object type and vice-


versa.
• So basically, object type can store any type of
data.
Types: Pointer
Types
• Pointer Types are similar to Reference Types. They store
memory addresses of variables of other types.

• C# pointers work the same way as C and C++ pointers.


However, they’re
considered unsafe. Thus, they can only be used in
unsafe context.
Variables &
Constants
Variables

• A Variable is a label given to a storage area in the Primary


Memory which stores some value.

• Each variable has a specific type which defines what type of


data the
variable will store.
Variables: Implicitly-typed Variables

• Variables can be created without specifying the type of the


variable.

• However, these variable must be (non-parameter) local


and must be
initialized during declaration.

• Instead of specifying the type of the variable, use the var


keyword.
Constants

• Constant is a fixed value which does not change during the


program.

• These are the categories of C# Constants:


• Integer Constants

• Float Constants

• Character Constants

• String Constants
Constants

• Integer Constants:
• It’s either a decimal or a hexadecimal value.

• Hexadecimal values have a prefix 0x or 0X.

• Unsigned Integer, Long and Unsigned Long have U or u, L or l


and UL or ul
suffixes respectively.
Constants

• Float Constants:
• It’s a float or a double value.

• A float value has a F or f suffix.

• A double value does not have any


suffix.
Constants

• Character Constants:
• Character Constants are enclosed in single
quotes.

• Character Constants can be either be a:

• A plain character

• An escape sequence
Constants

• Character Constants: Escape Sequences


• Escape Sequences are preceded by a back-slash (\)
character.

• These characters are transformed into another character at


run-time.
Escape sequence Meaning
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
Constants

• Character Constants: Escape


Sequences
Escape sequence Meaning
\r Carriage return
\t Horizontal tab
\v Vertical tab
\xHHH... Hexadecimal number of one or more digits
\uXXX… Unicode character
Constants

• String Constants:
• String is a collection of characters that is enclosed in double
quotes.

• Similar to character, they can contain plain characters and escape


sequences.

• It’s possible to create a verbatim strings in which the escape


sequences are ignored and all the characters are considered
plain.
Constants

• Making a variable constant:


• A variable can be declared as a constant using the const
keyword.

• A variable declared with const cannot be modified and it must be


initialized.
Operato
rs
Operators

• An operator is a special symbol that performs a certain


operation. These operations are either mathematical or logical.

• These operations are performed on operands which are


variables or
values.

• An operator can have one, two or three operands. These


operators are
known as Unary, Binary and Ternary operators respectively.
Operators

• Categories of Operators in
C#:
• Arithmetic Operators

• Relational Operators

• Logical Operators

• Bitwise Operators

• Assignment Operators

• Increment/Decrement
Operators

• Conditional Operator

• Miscellaneous Operators
Operators: Arithmetic Operators

• These operators perform basic mathematical operations on


operands.

Operator Description
+ Adds two operands
- Subtracts second operand from the first
* Multiplies both operands
/ Divides numerator by de-numerator
% Modulus Operator and remainder of after an integer division
Operators: Relational Operators

• These operators perform logical relation operations on


operands.
Operator Description

== Checks if the values of two operands are equal.

!= Checks if the values of two operands are not equal.

Checks if the value of left operand is greater than the


>
value of right operand.

< Checks if the value of left operand is less than the value of right
operand.
Checks if the value of left operand is greater than or equal to
>=
the value of right operand.

Checks if the value of left operand is less than or equal to


<=
the value of right operand.
Operators: Logical Operators

• These operators are used for joining relational


expressions.

Operator Description
Called Logical AND operator. If both the operands are non
&&
zero then condition becomes true.
Called Logical OR Operator. If any of the two operands is non
||
zero then
condition becomes true.
Called Logical NOT Operator. Use to reverses the logical
! state of its operand. If a condition is true then Logical NOT
operator will make false.
Operators: Bitwise Operators

• These operators are used for performing operations


on bits.

Operator Description

Binary AND Operator copies a bit to the result if it exists in both


&
operands.
| Binary OR Operator copies a bit if it exists in either operand.
Binary XOR Operator copies the bit if it is set in one
^
operand but not both.
Binary Ones Complement Operator is unary and has the effect
~ of
'flipping' bits.
Binary Left Shift Operator. The left operands value is moved left
<<
by the
number of bits specified by the right operand.
Binary Right Shift Operator. The left operands value is
>>
Operators: Assignment Operators

• These operators are used for assigning values to


variables.
Operator Description

Simple assignment operator, Assigns values from right side


=
operands to left side operand
Add AND assignment operator, It adds right operand to the left
+=
operand and assign the result to left operand
Subtract AND assignment operator, It subtracts right operand
-=
from the left operand and assign the result to left operand
Multiply AND assignment operator, It multiplies right operand
*=
with the left operand and assign the result to left operand

Divide AND assignment operator, It divides left operand with


/=
the right operand and assign the result to left operand

Modulus AND assignment operator, It takes modulus using two


%=
operands and assign the result to left operand
Operators: Increment/Decrement

• Increases or decreases the value of the


operand by 1.

• Can be prefixed or suffixed.


Operator Description
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
Operators: Conditional Operator

• Used for conditional assignment.

• It has 3 operands so it’s also known as Ternary


Operator.
Operators: Miscellaneous Operators

Operator Description

sizeof() Returns the size of a data type.


typeof() Returns the type of a class.
& Returns the address of an variable.
* Pointer to a variable.
is Determines whether an object is of a certain type.
as Cast without raising an exception if the cast fails.
Control
Structures
Control
Structures
 Control Structures are used for controlling the flow of the
execution.
 There are 2 types of Control Structures:
1. Decision Making Statements
• if…else if…else
• switch…case
2. Looping Statements
• for
• while
• do…while
• foreach
Control Structures: Decision Making

 Decision Making statements are used for branching the


execution flow of the program.
 if…else if…else:
 This statement allows to execute a block of code based on
condition(s).
 The conditions of the if and else if statements must evaluate to
a Boolean value (true or false).
 Whichever block’s condition evaluates to true will be executed,
rest of the blocks will be ignored.
 If none of the conditions match, the else block will be
executed.
 The curly braces are optional if the block contains only 1 line of
code.
Control Structures: Decision Making

 if…else if…
else:
Control Structures: Decision Making

 switch…case: Execute a block of code based on the value of


a variable.
Control Structures: Looping

 Looping Statements are used for executing a block of code


repeatedly.
 For loop:
 For loop repeats a block predefined number of times.
 It is an Entry Controlled loop because the condition is checked
before the body of loop is executed.
Control Structures: Looping

 While loop:
 While loop repeats a block predefined or unknown number of
times.
 It is an Entry Controlled loop because the condition is checked
before the
body of loop is executed.
Control Structures: Looping

 Do…while loop:
 Do…while loop repeats a block predefined or unknown number
of times.
 It is an Exit Controlled loop because the condition is checked
after the
body of loop has been executed at least once.
Control Structures: Looping

 Foreach loop:
 Foreach loop is used for iterating through the elements of an
array or a
collection.
 It copies individual values from the collection into a variable
as the loop progresses.
Control Structures: Looping

 A look can be terminated prematurely by using the break


keyword which will skip all the remaining iterations
(repetition) of the loop.
 For skipping a singe iteration, the continue statement
can be used.
 The break and continue statements can be used by all 4
type of loops.
Type
Conversion
Type Conversion

 Type Conversion means to convert one type to


another.
 There are 2 ways type conversion can be
performed:
 Implicit Type Conversion
 Explicit Type Conversion
Type Conversion: Implicit Type
Conversion
 These conversions are performed automatically by .NET in a
type-safe manner.
 Such as:
 Converting smaller integral types to larger ones.

 Converting derived class objects to base class


objects.
Type Conversion: Explicit Type
Conversion
 These conversions are performed manually by the
developer using either casting operator or built-in
methods.
 These conversions are not usually type-safe, so there are
chances of
data loss.
 Explicit Type Conversion is required in cases such as
converting larger type to smaller one or converting parent
class object to child class object.
 C# provides 2 casting operators.
Type Conversion: Explicit Type
Conversion
 Casting operator:
 One of the Casting Operator is the type written in round
brackets
before the variable or the value which is to be
converted.
 However, if the conversion is not successful, an
exception will be thrown.
Type Conversion: Explicit Type
Conversion
 Casting operator:
 Another Casting Operator is the as keyword.
 If the conversion is not successful, no exceptions will
be thrown
and null will be returned
 Moreover, as operator cannot be used with Value
Types.
Type Conversion: Explicit Type
Conversion
 Type Conversion Methods:
 .NET provides a Convert class which contains the
following static
methods for converting types.

Method Description

ToBoolean Converts a type to Boolean type


ToChar Converts a type to character type
ToByte Converts a value to byte type
ToDecimal Converts a value to decimal type
ToDouble Converts a type to double
ToString Converts a type to string
Type Conversion: Explicit Type
Conversion
 Type Conversion
Methods:
Method Description

ToInt16 Converts a type to short (16-bit integer)


ToInt32 Converts a type to int (32 bit integer)
ToInt64 Converts a type to long (64 bit integer)
ToUInt16 Converts a type to ushort (unsigned 16 bit
integer)
ToUInt32 Converts a type to uint (unsigned 32 bit integer)
ToUInt64 Converts a type to ulong (unsigned 64 bit integer)
Type Conversion: Explicit Type
Conversion
 Type Conversion Methods:
 The System.Object class provides a method ToString( )
which can
be used to convert any type to string.
 The Object class is the parent of all other classes,
meaning the
ToString( ) method is also available in all of its children.
Array
s
Arrays

 Arrays are fixed-size collection of values of the same type


under a single name which are stored in a contiguous
manner in the Memory.
 These values are known as Elements. Each value (element)
has a 0-
based index.
 The base/parent of any array is System.Array class.
 Dimension-wise, there are 3 types of arrays in C#:
 Single Dimensional Array
 Multi-Dimensional Array
 Jagged Array
Arrays: Single Dimensional Array

 The elements of a Single Dimensional Array are atomic


type values.

 Array Initializers are used for initializing an array with


predefined values.
 Array elements can be accessed using their indices.
Arrays: Single Dimensional Array
Arrays: Multi-Dimensional Array

 The elements of a Multi-Dimensional Array are other


arrays.
 It is an array of arrays.
 It’ll create a matrix of rows x columns.
 Each row will have same number of cells.
Arrays: Multi-Dimensional Array
Arrays: Jagged Array

 Jagged Array is an array of arrays where each array can


have different number of elements.
 Basically, it’s a table where each row may have different
number of
cells.
Arrays: Jagged Array
Pointer
s
Pointers

 A pointer stores address of a Value Type or an Enumeration


variable.
 Pointers cannot point to Reference Types because Garbage
Collector
does not support pointers.
 Pointers are considered unsafe in C#. They must be created
inside an
unsafe context (block, method or class).
 Use the unsafe keyword to create a block, or add it to a
method or class definition.
 Moreover, a C# program containing a pointer must be
compiled with the Allow Unsafe Code option enabled in
Pointers
Classes &
Objects
Object

 An Object is a basic runtime entity in an Object-Oriented


Application.
 An Object contains data and its related functionalities.
 An Object has 3 characteristics:
 Identity
 Properties / States
 Functionalities / Behaviours
Class

 Class is a user-defined type which describes what


properties and functionalities an Object will contain.
 An Object is a variable or an instance of a class.
 A Class can contain various members such as variables,
functions, classes, enumerations and such.
 Inside a class, variables are known as Fields or Instance
Variables and the functions are known as Methods.
 The class itself and all of its members are bound by an
Access Modifier
which describes the visibility of the class and its members.
Class: Access Modifiers

 Access Modifiers specify the visibility of class and its


members.
 In C#, there are 6 access modifiers:
 private: Accessible only within the same class.
 protected: Accessible within the same class and children
classes.
 public: Accessible everywhere.
 internal: Accessible everywhere within the same
assembly.
 protected internal: Accessible within the same
assembly or the children classes from different
Assembly.
Classes & Objects

 If an access modifier is not specified, then by default the


access of a class is internal and access of members is
private.
 A top-level class can only be public or internal.
 An object of a class is created using the new memory
management operator.
Classes & Objects
Classes & Objects: Static Members

 A class can also have static members.


 Static Members have the following
characteristics:
 They are shared between all the objects of
a class.
 They are accessible directly using class
name.
 Static methods can only access static
variables.
Classes & Objects: Static Members
Classes & Objects: Static Class

 A class can be declared as static. It has the following


characteristics:
 It can only contain static members.
 Its object cannot be created.
 It cannot be inherited.

Click here for the


program
Classes & Objects: Partial Classes

 A class can be divided into multiple files using the partial


keyword.
 At compile-time, partial classes are merged into a single
class.
 Characteristics:
 The same partial class must have same name, accessibility and
must be in the same namespace.
 If a single partial class inherits, is abstract or sealed, then it’ll be
applied on all partial classes.
 Advantages:
 Multiple developers can work on a single class at the same time.
 Visual Studio uses this feature to separate the Windows Forms
Classes & Objects: Partial Classes
Classes & Objects: Constructor

 Constructor is a special method of a class with the


following characteristics:
 It has the same name as class and does not have
any return type.
 It’s called automatically when an object of the
class is created.
 The purpose of a constructor is to initialize the data
members of the object.
 These are the types of Constructors in C#:
 Default Constructor
 Parameterized Constructor
 Static Constructor
Classes & Objects: Constructor

 Default Constructor:
 It does not accept any parameters. If a constructor is not
specified, C#
automatically adds a default constructor.
Classes & Objects: Constructor

 Parameterized Constructor:
 It accepts 1 or more parameters which will be used to
initialize the data
member of the class when the object is created.
Classes & Objects: Constructor

 Static Constructor:
 Static Constructor is created using the static
keyword.
 No access modifier is specified for a static
constructor.
 It cannot accept any parameters.
 It’s called automatically when the class is loaded into
memory.
Classes & Objects: Constructor

 Private Constructor:
 It’s a default or a parameterized constructor which has a
private access
modifier.
 An object of a class cannot be created which is having
a Private Constructor.
 Private Constructors are generally created in a class
which only has static
members to prevent object creation.
Classes & Objects: Destructor

 Destructor is a special method which is automatically called


when the object is being collected (destroyed) by the
Garbage Collector.
 Characteristics of Destructor:
 It’s name is same as class name with tilde symbol (~) as
prefix.
 A Destructor cannot have access modifiers or parameters.
 It is called automatically when GC destroys the object.
Encapsulati
on
Encapsulation

 Encapsulation is the process of hiding internal details of an


object and showing only required information to other
objects.
 Encapsulation prevents unauthorized access to the data of
an object.
 In C#, Encapsulation is implemented by creating a class and
making its sensitive members private.
Inheritan
ce
Inheritance

 Inheritance means a class obtains properties and


functionalities of another class.
 It is a code re-usability mechanism for creating new
classes from
existing ones rather than creating from scratch.
 This generally defines is relationship between parent and
child classes.
 For example, Computer is a Machine where Computer
is the child class and Machine is the parent class.
Inheritance

 Parent class is also known as Base Class or Super Class


and child class is also known as Derived Class or Sub
Class.
 Private members cannot be inherited.
 C# supports 4 types of Inheritance
1. Single
2. Multi-level
3. Hierarchical
4. Hybrid
 Multiple Inheritance is not supported in C#, however
it can be emulated using interface.
Inheritan
ce
Singe Inheritance 1 parent,
1 child
Inheritan
ce
Multi-Level Inheritance Grandparent, parent, child
and so on…
Inheritan
ce
Hierarchical Inheritance 1 parent, multiple
children
Inheritan
ce
Hybrid Inheritance Combination of
various types
Inheritance

Accessing base class members:


 The members of the parent class can be accessed directly inside the
child class;
this keyword can also be used.
 C# also provides base keyword to access the members of parent
class within child class.
 Using base is only necessary when parent and child both has
members with
same name.
 In above case, accessing member normally or with this refers to the
member of child accessing with base refers to the member of

parent.
Inheritan
ce
Accessing base class
members:
Inheritance

Parent with Parameterized Constructor:


 If the parent has a parameterized constructor, then the parameters
have to be
passed through the child’s constructor.
 The call to the parent’s constructor is specified right after the
argument list of the child constructor using the base keyword like
a method call following a colon sign:
Inheritan
ce
Parent with Parameterized
Constructor:
Polymorphis
m
Polymorphis
m
 Polymorphism means one name, many forms.
 A single name or symbol can be used for more than one type
of tasks.
 For example:
 The + operator can be used for adding numbers as well as
joining strings.
 The – operator can be used for subtracting numbers
as well as representing negative numbers.
Polymorphis
m
There are 2 types of Polymorphism in C#:
 Compile-time (Static) Polymorphism:
 The “form” of the name/symbol to be used is decided by the
compiler when
the program is compiled.
 These are the types of Static Polymorphism:
 Method Overloading
 Operator Overloading
 Run-time (Dynamic) Polymorphism:
 The “form” of the name/symbol to be used is decided at runtime.
 These are the types of Dynamic Polymorphism:
 Method Overriding
Polymorphism: Method Overloading

 Method Overloading means a class contains multiple


methods with same name but their number and/or types of
parameters are different.
 The compiler matches the number and/or type of parameters
passed
and decides which method to call at compile-time.
 If no matches are found, an error will be thrown by the
compiler and the program will not run.
Polymorphism: Method Overloading
Polymorphism: Operator Overloading

 Built-in operators do not accept the operands of user-defined


types.
 It’s possible to do so by creating an operator method in the
class.
 The operator method must be static.
 Number and Type of args will be same as the number
and type of operands.
 The return type depends on what type of operator is
being overloaded.
 For example: Arithmetic operator methods should return the
same type as the operands and Relational operator methods
should return a Boolean value.
Polymorphism: Operator Overloading

Click here for the


program
Polymorphism: Method Overriding

 Method Overriding means a child class replaces the


method of a parent by re-creating the same method with
exact same signature.
 Only abstract, virtual or override methods of the
parent can be
overridden. Doing otherwise can result in error or
unexpected behavior.
 The override keyword must be present when overriding a
method in the child class.
 This makes sure that even if an object of child is assigned to a
reference of parent, calling the overridden method still calls
the child’s method.
Polymorphism: Method Overriding

Click here for the


program
Abstract
Class
Abstract Class

 Abstract class works as a parent class and provides common


specifications or implementations that can be used by
children classes.
 An object of an Abstract class cannot be created. Its sole
purpose is to
act as a parent.
 Like a normal class, abstract class can have all kinds of
members and additionally, it can have abstract methods.
 Abstract methods must be overridden by the child class, not
doing so will yield compiler error.
Abstract Class

 Abstract class can have constructors and destructors which


are invoked when the child class objects are created and
destroyed.
 It’s recommended (not a requirement) to suffix abstract
classes with
“Base” to easily distinguish them from normal classes.

Click here for the


program
Sealed
Class
Sealed Class

 Making a class sealed prevents it from being


inherited.
 A sealed class cannot have virtual methods.
Interfac
e
Interface

 Interface provides a syntactical structure a class should follow.


 They’re used for enforcing a particular structure on the classes
that
implements it.
 An Interface can have declarations of methods, indexers,
properties and events.
 By default, all the members of an interface are public and
abstract.
 Interfaces are implemented, not inherited. A class can
implement multiple interfaces, giving a sense of multiple
inheritance.

Interface

 The objects of implementing classes can be assigned to


references of the interface.
 In .NET, generally interface names have an “I” prefix to
easily distinguish
them from classes.

Click here for the


program
Propertie
s
Properties

 Properties are a mechanism to read and modify private fields


of a class.
 A Property contains Accessors which contain executable
statements for
getting (reading) and setting (writing/modifying) field values.
 The accessor used for getting field value is known as Get
Accessor and the one used for setting field value is known as
Set Accessor.
 A Property must contain either Set Accessor or Get
Accessor or both.
 Inside a Property, the following Contextual Keywords are
used:
Properties

Click here for the


program
Indexe
rs
Indexers

 An Indexer is a special type of property that allows indexing


of an object. When a class has an indexer, its object can
behave as an array.
 The this keyword is used as the name of the property.
 It takes an index (kind of a parameter) and may return a
value.
Indexers

 Synta
x:

Click here for the


program
Enumeratio
ns
Enumerations

 An enumeration is a set of named integer constants.


 It’s created using the enum keyword.
 Enumerations are user-defined Value Types.
 Each enum value will have a constant associated, starting
from 0.
 An enum value can be assigned a user-defined constant;
doing so will cause the following unassigned values to have
incrementing constants.
 The purpose of enum is to describe a constant, making the
code more readable.
Enumerations

Click here for the


program
Pass by
Reference
Pass by
Reference
 All the Value Types are, by default, passed by value as
a method parameter: Copies are passed instead of
actual values.
 All the Reference Types are passed by reference:
Instead of copies, the
reference of the objects are passed to methods.
 To pass references of Value Types, C# provides 2
keywords: ref and out
 Rules for ref:
 Must be initialized.
 The value of variable may or may not change in the
method
Pass by
Reference
Collectio
ns
Collections

 Collections are specialized classes for data storage and


retrieval which uses various data structures such as Queue,
Stack, List and Hash Tables.
 .NET supports 3 types of collections:
 Non-generic Collections
 Generic Collections
 Specialized Collections
 Most of the Collection classes (directly or indirectly)
implement the ICollection interface.
Collections: Non-generic

 Non-generic collections can store and retrieve object type


of data.
 It can store any type of data because all types derive from
the object
type in .NET.
 However, when retrieving data from a non-generic
collection, it will return only object type, so a type
conversion is generally required to convert the value to its
original type.
Collections: Non-generic

ArrayList:
 An ordered list of items (think of it as a dynamic array).
 Each item can be accessed/updated individually using its 0-
based index.
 Supports item addition, insertion, updating and removal.
 Resizes automatically as items are added/removed.
 Click here for an example
Collections: Non-generic

Hashtable:
 A collection of key-value pairs.
 Supports custom indexing. May not maintain ordering.
 Each item can be accessed/updated individually using its
custom index.
 Click here for an example
Collections: Non-generic

SortedList:
 A list of key-value pairs, supports 0-based indexing and custom
indexing.
 Basically, a combination of ArrayList and Hashtable.
 Items are sorted by Keys.
 Click here for an example
Collections: Non-generic

Stack:
 Stores and retrieves data using Last-In-First-Out (LIFO)
approach.
 Click here for example
 Supports Push, Pop and Peek operations:
 Push adds an item at the Top of the Stack (TOS)
 Pop removes an item from the TOS and returns it.
 Peek returns an item from the TOS without removing
it.
 Click here for an example
Collections: Non-generic

Queue:
 Stores and retrieves data using First-In-First-Out (FIFO)
approach.
 Supports Enqueue, Dequeue and Peek operations:
 Enqueue appends an item into the queue.
 Dequeue removes an item from the end and returns
it.
 Peek returns an item from the end without removing
it.
 Click here for an example
Collections: Generic

 Generic collections can store and retrieve only specific type


of data.
 .NET provides generic collection classes such as:
 List<T> (Generic version of ArrayList, supports all operations of
ArrayList)
 Stack<T> (Generic version of Stack, supports all operations of
Stack)
 Queue<T> (Generic version of Queue, supports all operations
of Queue)
Delegat
es
Delegates

 A Delegate is an object which holds a references to a Method.


 Primary purpose of delegates is to provide call-back mechanism for
events.
 All delegates are derived from System.Delegate type.
 A delegate can refer to a method which has the same signature
(arguments and return type) as itself.
 There are 2 types of delegates:
1. Simple delegates
2. Multicast delegates
Delegates: Simple Delegates

 A simple delegate can hold reference to a single


method.
 Creating a delegate:
 Syntax:
 Example:
 Using the delegate:
 Create an object of the delegate,
and pass a method of matching
signature in the constructor without ( ).
 Now, “call” the delegate
object just like a method.
 Click here for an example
Delegates: Multicast Delegates

 It’s possible to create a delegate which refers to multiple


methods.
 Create multiple objects of the same delegate referring to single
methods.

 Add the using the + operator and assign the result into a 3rd
delegate object.

 Call the 3rd delegate object as a method.

 Click here for an example


Even
ts
Events

 Events are some occurrence of a user action, such as, key press,
button click.
 C# provides a mechanism to call a method when an event occurs.
 Before using events, their delegates must be created.
 Basically, events are a collections of delegates which are called
when user performs a specific operation.
 See this example
 Methods can be added into an event using += operator and,
similarly, removed
using -= operator.

You might also like