C Sharp Notes by Ashok
C Sharp Notes by Ashok
94
2 PG Mates / RoomSharing / Flat Mates React+Springboot+MySql
21
3 Tour and Travel management System React+Springboot+MySql
59
5 HomeRental Booking System React+Springboot+MySql
07
6 Event Management System React+Springboot+MySql
80
8 Agriculture web Project React+Springboot+MySql
9 AirLine Reservation System / Flight booking System React+Springboot+MySql
.in
10 E-commerce web Project React+Springboot+MySql
ys
11 Hospital Management System React+Springboot+MySql
ra
12 E-RTO Driving licence portal React+Springboot+MySql
13 Transpotation Services portal
ar
React+Springboot+MySql
14 Courier Services Portal / Courier Management System React+Springboot+MySql
ith
15 Online Food Delivery Portal React+Springboot+MySql
w
16 Muncipal Corporation Management React+Springboot+MySql
17 Gym Management System de React+Springboot+MySql
co
18 Bike/Car ental System Portal React+Springboot+MySql
19 CharityDonation web project React+Springboot+MySql
20 Movie Booking System React+Springboot+MySql
freelance_Project available to buy contact on 8007592194
21 Job Portal web project React+Springboot+MySql
22 LIC Insurance Portal React+Springboot+MySql
23 Employee Management System React+Springboot+MySql
94
24 Payroll Management System React+Springboot+MySql
25 RealEstate Property Project React+Springboot+MySql
21
26 Marriage Hall Booking Project React+Springboot+MySql
27 Online Student Management portal React+Springboot+MySql
59
28 Resturant management System React+Springboot+MySql
29 Solar Management Project React+Springboot+MySql
07
30 OneStepService LinkLabourContractor React+Springboot+MySql
31 Vehical Service Center Portal React+Springboot+MySql
80
32 E-wallet Banking Project React+Springboot+MySql
33 Blogg Application Project React+Springboot+MySql
34 Car Parking booking Project React+Springboot+MySql
.in
35 OLA Cab Booking Portal React+Springboot+MySql
36 Society management Portal React+Springboot+MySql
ys
37 E-College Portal React+Springboot+MySql
38 FoodWaste Management Donate System React+Springboot+MySql
ra
39 Sports Ground Booking React+Springboot+MySql
ar
40 BloodBank mangement System React+Springboot+MySql
41 Bus Tickit Booking Project React+Springboot+MySql
ith
42 Fruite Delivery Project React+Springboot+MySql
43 Woodworks Bed Shop React+Springboot+MySql
w
44 Online Dairy Product sell Project React+Springboot+MySql
45
46
Online E-Pharma medicine sell Project
FarmerMarketplace Web Project
de
React+Springboot+MySql
React+Springboot+MySql
co
47 Online Cloth Store Project React+Springboot+MySql
48 React+Springboot+MySql
49 React+Springboot+MySql
50 React+Springboot+MySql
DOTNET NOTES BY ASHOK PATE
94
the problems posed by traditional languages.
21
We can use C# for building variety of applications
59
WINDOWS APPLICATION: using console application or winform application.
07
MOBILE APPLICATIONS: for phones such as Nokia Lumia (built-in support) but we
can use a third party tool or library called “XAMARIN” to create mobile applications for
80
ANDROID and IOS as well.
WEB APPLICATON: using [Link] web forms or [Link] MVC.
GAMING APPLICATION: Unity. .in
C# could theoretically be compiled to machine code, but in real life, it's always used in
combination with the .NET framework. Therefore, applications written in C#, requires
ys
the .NET framework to be installed on the computer running the application. While
ra
the .NET framework makes it possible to use a wide range of languages, C# is sometimes
referred to as THE .NET language, perhaps because it was designed together with the
ar
framework.
ith
Language interoperability is the ability of code to interact with code that is written by
using a different programming language.
w
.NET is a programming framework created by Microsoft that developers can use to create
co
applications more easily. A framework is just a bunch of code that the programmer can
call without having to write it explicitly.
It provides a controlled programming environment where software can be developed,
installed and executed on Windows-based operating systems.
It is basically a collection of libraries.
Is a programming platform that is used for developing Windows, Web-based, and mobile
software.
It has a number of pre-coded solutions that manage the execution of programs written
specifically for the framework.
pg. 1
DOTNET NOTES BY ASHOK PATE
A programmer can develop applications using one of the languages supported by .NET.
Microsoft introduced C# as a new programming language to address the problems posed
by traditional languages.
The .NET Framework is an infrastructure that is used to build, deploy, and run different
types of applications and services using .NET technologies.
The .NET Framework is an infrastructure that is used to Minimize software development,
deployment, and versioning conflicts.
94
Create a very simple and yet powerful tool for building interoperable and robust
21
applications.
Create a complete object-oriented architecture.
59
Support powerful component-oriented development.
Allow access to many features previously available only in C++ while retaining the ease-
07
of-use of a rapid application development tool such as Visual Basic.
Provide familiarity to programmers coming from C or C++ background.
80
Allow to write applications that target both desktop and mobile devices.
C# has features common to most object-oriented languages.
Provide consistent object-oriented programming environment.
.in
Minimize software deployment and versioning conflicts by providing a code-execution
environment.
ys
Promote safe execution of code by providing a code-execution environment.
ra
o Generics
o Indexers
de
applications.
C# is a programming language designed for building a wide range of applications that run
on the .NET Framework.
Purpose of C# Language
Microsoft .NET was formerly known as Next Generation Windows
Services (NGWS).
pg. 2
DOTNET NOTES BY ASHOK PATE
94
C# is an object-oriented language derived from C and C++.
The motive of C# is to provide a simple, efficient, productive, and
21
59
revolutionary.
07
Features of C#
80
C# is a programming language designed for building a wide range of
applications that run on the .NET Framework.
.in
Following are some basic key features of C#:
o Type-safety Checking
ys
o Object-oriented Programming
ra
o Garbage Collection
ar
Association (ECMA)
o Generic Types and Methods
w
o Iterators
de
o Static Classes
o Nullable Types
o Auto-implemented Properties
o Accessor Accessibility
o Anonymous Methods
o Parallel Computing
o Auto-implemented Properties
pg. 3
DOTNET NOTES BY ASHOK PATE
o Partial Classes
Object-oriented Programming: Focuses on objects so that code
written once can be reused. This helps reduce time and effort on the
part of developers.
Type-safety Checking: Checked the overflow of types because
uninitialized variables cannot be used in C# as C# is a case-sensitive
94
language
Garbage Collection: Performs automatic memory management from
21
time to time and spares the programmer the task.
Standardization by European Computer Manufacturers Association
59
07
C# programs.
Generic Types and Methods: Are a type of data structure that
80
contains code that remains the same throughout but the data type of
the parameters can change with each use. .in
Iterators: Enable looping (or iterations) on user-defined data types
ys
with the for each loop.
Static Classes: Contain only static members and do not require
ra
instantiation.
ar
Partial Classes: Allow the user to split a single class into multiple
ith
method argument with a name rather than its position in the argument
list.
Methods with optional Arguments: Allow the user to define a method
with an optional argument with a default value.
Nullable Types: Allow a variable to contain a value that is undefined.
Accessor Accessibility: Allows the user to specify the accessibility
levels of the get and set accessors.
pg. 4
DOTNET NOTES BY ASHOK PATE
94
There are Several Applications Of C#
21
C# is an object-oriented language that can be used in a number of
applications.
59
Gaming applications
07
Web applications
80
Mobile applications for pocket PCs, PDAs, and cell phones
Web services
Cloud applications .in
Simple standalone desktop applications such as Library Management
ys
Systems, Student Mark Sheet generation, and so on
ra
cities or countries
ith
w
The CLR
de
Manages the execution of programs and provides a suitable environment for programs to run.
Provides a multi-language execution environment.
Is a backbone of .NET Framework
Performs various functions such as:
o Memory management
o Code execution
o Error handling
o Code safety verification
o Garbage collection
pg. 5
DOTNET NOTES BY ASHOK PATE
94
language compilers in its Software Development Kit (SDK).
21
For Example
59
To display a text message on the screen, the following command can
be used:
07
[Link](".NET Architecture");
80
The same WriteLine() method will be used across all .NET
languages.
.in
This is done by making the Framework Class Library as a common
class library for all .NET languages.
ys
on the Web.
de
[Link]
Entity Framework
Task Parallel Library
LINQ
Parallel LINQ
The .NET Framework languages, such as C#, VB, and J# are statically
94
typed languages.
21
CLS - Common Language Specification
59
Is a set of rules that any .NET language should follow to create
applications that are interoperable with other languages.
07
CTS - Common Type System
80
Describes how data types are declared, used, and managed in the
.in
runtime and facilitates the use of types across various languages.
ys
[Link]
ra
ith
[Link]
w
WPF
Is a UI framework based on XML and vector graphics.
Uses 3D computer graphics hardware and Direct3D technologies to
create desktop applications with rich UI on the Windows platform.
LINQ
94
Is a component that provides data querying capabilities to a .NET
application.
21
59
Entity Framework
07
Is a set of technologies built upon [Link] that enables creating
data-centric applications in object-oriented manner.
80
Parallel LINQ
.in
Is a set of classes to support parallel programming using LINQ.
ys
pg. 8
DOTNET NOTES BY ASHOK PATE
94
21
The following figure represents the process of conversion of CIL code
59
to the native code:
07
80
.in
ys
ra
ar
ith
w
de
co
94
Thread management
Remoting
21
Memory management
59
Below figure shows a more detailed look at the working of the CLR:
07
80
.in
ys
ra
ar
ith
w
de
co
The compiler converts the source code into executable code that can
be run by the users.
One of the primary goals of .NET Framework is to combine the
runtime environments so that the developers can work with a single
set of runtime services.
When the code written in a .NET compatible language such as C# or
VB is compiled, the output code is in the form of MSIL code.
94
MSIL is composed of a specific set of instructions that indicate how
the code should be executed.
21
MSIL is now called as Common Intermediate Language (CIL).
59
The following figure depicts the concept of CIL:
07
80
.in
ys
ra
ar
ith
w
pg. 11
DOTNET NOTES BY ASHOK PATE
94
Garbage Collection is the process of automatic reclaiming of memory
21
from objects that are no longer in scope.
Garbage Collection helps the process of allocating and de-allocating
59
07
Below figure describes concept of garbage collection:
80
.in
ys
ra
ar
ith
w
de
co
pg. 12
DOTNET NOTES BY ASHOK PATE
94
Provides dynamic features to the existing statically typed languages.
For example, C# relies on the DLR to perform dynamic binding.
21
----------------------------------------------------------------------------------------------------------------------------------------------------------------
59
Common Language Runtime (Clr) In Dotnet
07
Framework
80
The CLR:
o Is the foundation of the .NET Framework. .in
o Acts as an execution engine for the .NET Framework.
ys
o Manages the execution of programs and provides a suitable
ra
The following figure shows a more detailed look at the working of the CLR:
w
de
co
MSIL
pg. 13
DOTNET NOTES BY ASHOK PATE
F1 F2 F3 F2
94
21
59
07
When a code is executed for the first time;
The CIL (COMMON INTERMEDIATE LANGUAGE) code is converted to a code
80
native to the operating system.
This is done at runtime by the Just-In-Time (JIT) compiler present in the CLR.
.in
The CLR converts the CIL code to the machine language code.
ys
Once this is done, the code can be directly executed by the CPU
ra
--------------------------------------------------------------------------------------------------------------
ar
ith
What Is Namespace In C# ?
w
pg. 14
DOTNET NOTES BY ASHOK PATE
94
21
59
07
80
Purpose Of Namespaces
Scenario .in
ys
Consider Venice, which is a city in the US as well as in Italy.
You can easily distinguish between the two cities by associating them
ra
By doing this, classes can have identical names without any resultant
name clashes.
The following code renames identical classes by inserting a descriptive
prefix:
class SamsungTelevision
{
...
}
pg. 15
DOTNET NOTES BY ASHOK PATE
class SamsungWalkMan
{
...
}
class SonyTelevision
{
...
}
class SonyWalkMan
{
...
}
94
In Above Code,
21
The identical classes Television and WalkMan are prefixed with their
59
respective company names to avoid any conflicts.
There cannot be two classes with the same name.
07
It is observed that the names of the classes get long and become
80
difficult to maintain.
The following code demonstrates a solution to overcome this, by using
.in
namespaces:
ys
namespace Samsung
{
ra
class Television
{
ar
...
}
ith
class WalkMan
{
...
w
}
de
}
namespace Sony
{
co
class Television
{
...
}
class Walkman
{
...
}
}
In Above Code,
pg. 16
DOTNET NOTES BY ASHOK PATE
94
This identifier helps you to access the classes within the namespace.
21
Apart from classes, the following data structures can be declared in a
namespace:
59
Interfaces
07
An interface is a reference type that contains declarations of the
80
Structures
ra
ar
A structure is a value type that can hold values of different data types.
It can include fields, methods, constants, constructors, properties,
ith
Enumeration
co
94
21
A namespace allows you to add more classes, structures,
enumerations, delegates, and interfaces once the namespace is
59
declared.
07
A namespace includes classes with names that are unique within the
namespace.
80
A namespace provides the following benefits:
.in
A namespace allows you to use multiple classes with same names by
ys
creating them in different namespaces.
It makes the system modular.
ra
contain:
ith
o Classes
w
o Interfaces
de
o Structures
o Delegates
co
o Enumerations
namespaces.
pg. 18
DOTNET NOTES BY ASHOK PATE
94
[Link]
21
The [Link] namespace contains classes and interfaces
59
that define complex data structures such as lists, queues, bit arrays,
hash tables, and dictionaries.
07
[Link]
80
The [Link] namespace contains classes that make up the
[Link] architecture. .in
The [Link] architecture allows you to build components that can
ys
be used to insert, modify, and delete data from multiple data sources.
ra
[Link]
ar
ith
[Link]
The [Link] namespace contains classes that enable you to read
from and write to data streams and files.
[Link]
pg. 19
DOTNET NOTES BY ASHOK PATE
94
The following figure displays some built-in namespaces:
21
59
07
80
.in
ys
ra
ar
ith
w
de
pg. 20
DOTNET NOTES BY ASHOK PATE
94
The two approaches of referencing the System namespace are:
21
59
07
80
.in
ys
ra
ar
ith
w
recommended.
co
In Above Syntax,
NamespaceName: Is the name of the namespace.
pg. 21
DOTNET NOTES BY ASHOK PATE
94
using <NamespaceName>.<ClassName>;
In Above Syntax,
21
59
NamespaceName: Is the name of the namespace and it will refer to
all classes, interfaces, structures, and enumerations.
07
ClassName: Is the name of the specific class defined in the
80
namespace that you want to access.
The following code demonstrates the use of the using keyword with
.in
namespaces:
ys
using System;
class World
ra
{
static void Main(string[] args)
ar
{
[Link](“Hello World”);
ith
}
}
w
In Above Code,
de
The System namespace is imported within the program with the using
co
keyword.
If this were not done, the program would not even compile as the
Console class exists in the System namespace.
Output
Hello World
pg. 22
DOTNET NOTES BY ASHOK PATE
94
}
}
21
In Above code, the class is not imported, but the System namespace
59
members are used along with the statements.
07
Output
80
Hello World
This is C# Programming
You have executed a simple program of C# .in
ys
Custom Namespaces
ra
Custom namespaces:
co
pg. 23
DOTNET NOTES BY ASHOK PATE
//type-declarations;
}
In Above Syntax:
NamespaceName: Is the name of the custom namespace.
type-declarations: Are the different types that can be declared. It can
be a class, interface, struct, enum, delegate, or another namespace.
94
The following code creates a custom namespace named Department:
21
namespace Department
{
59
class Sales
{
static void Main(string [] args)
07
{
[Link](“You have created a custom namespace
named Department”);
80
}
}
}
In Above code,
.in
ys
Department is declared as the custom namespace.
ra
Output
ith
94
grouping of similar types and any programmer will be easily
able to search for similar classes.
21
o Creating deep hierarchies that are difficult to browse must be
59
avoided.
o Creating too many namespaces must be avoided for simplicity.
07
What Is Main Method ?
80
Main method is the entry point of your application. .in
-------------------------------------------------------------------------------------------------------------
ys
users.
de
The programmer can use the command line interface to display the
output.
co
The programmer can similarly accept inputs from a user through the
command line interface.
Such input and output operations are also known as console
operations.
Console Operations
Following are the features of the console operations:
pg. 25
DOTNET NOTES BY ASHOK PATE
94
prompt.
All console applications consist of three streams, which are a series
21
of bytes. These streams are attached to the input and output devices
59
of the computer system and they handle the input and output
operations.
07
There are 3 streams:
80
1. Standard in .in
2. Standard out
ys
3. Standard err
ra
Standard in
ar
The standard in stream takes the input and passes it to the console
ith
Standard out
de
co
pg. 26
DOTNET NOTES BY ASHOK PATE
In C#, all console operations are handled by the Console class of the
System namespace.
A namespace is a collection of classes having similar functionalities.
To write data on the console, you need the standard output stream,
provided by the Console class.
There are two output methods that write to the standard output stream
as follows:
94
o [Link](): Writes any type of data.
21
with a new line character in the standard output stream. This
59
means any data after this line will appear on the new line.
07
The following syntax is used for the [Link]() method, which
allows you to display the information on the console window:
80
[Link](“<data>” + variables);
Where,
.in
ys
data: Specifies strings or escape sequence characters enclosed in
ra
double quotes.
ar
on the console.
w
[Link](“<data>” + variables);
The following code shows the difference between the [Link]() and
[Link]() methods:
[Link](“C# is a powerful programming language”);
[Link](“C# is a powerful”);
[Link](“programming language”);
[Link](“C# is a powerful”);
[Link](“ programming language”);
pg. 27
DOTNET NOTES BY ASHOK PATE
Output
C# is a powerful programming language
C# is a powerful
programming language
C# is a powerful programming language
94
What Are Placeholders?
21
The WriteLine() and Write() methods accept a list of parameters to
59
format text before displaying the output.
07
The first parameter is a string containing markers in braces to
indicate the position, where the values of the variables will be
80
substituted. Each marker indicates a zero-based index based on the
number of variables in the list.
.in
The following code uses placeholders in the [Link]()
method to display the result of the multiplication operation:
ys
ra
Output
de
input methods that enable the software to take in the input from the
standard input stream.
These methods are as follows:
o [Link](): Reads a single character.
The following code reads the name using the ReadLine() method and
94
displays the name on the console window:
21
string name;
[Link](“Enter your name: “);
name = [Link]();
59
[Link](“You are {0}”,name);
07
In Above Code,
80
The ReadLine() method reads the name as a string and the string that
is given is displayed as output using placeholders.
Output
.in
ys
Enter your name: David Blake
ra
[Link]() method:
w
using System;
de
class Loan
{
co
pg. 29
DOTNET NOTES BY ASHOK PATE
In Above code,
The name and loan amount are accepted from the user using the
[Link]() method. The details are displayed on the console
94
using the [Link]() method.
21
The placeholders {0}, {1}, and {2} indicate the position of the first,
second, and third parameters respectively.
59
The 0 specified before # pads the single digit value with a 0. The
07
#option specifies the digit position.
The % option multiplies the value by 100 and displays the value
80
94
The following is the syntax for the numeric format specifier:
21
[Link](“{format specifier}”, <variable name>);
Where,
59
07
formatspecifier: Is the numeric format specifier.
variable name: Is the name of the integer variable.
80
Numeric format specifiers work only with numeric data that can be
suffixed with digits. The digits specify the number of zeros to be inserted,
.in
after the decimal location.
ys
Example
ra
ar
If you use a specifier such as C3, three zeros will be suffixed, after
ith
the decimal location of the given number. The following table lists
some of the numeric format specifiers in C#:
w
de
co
pg. 31
DOTNET NOTES BY ASHOK PATE
94
21
59
07
Custom numeric format strings contain more than one custom
80
numeric format specifiers and define how data is formatted.
A custom numeric format string is defined as any string that is not a
.in
standard numeric format string. The following table lists the custom
numeric format specifiers and their description:
ys
ra
ar
ith
w
de
co
pg. 32
DOTNET NOTES BY ASHOK PATE
94
21
59
07
80
.in
ys
The following code demonstrates the conversion of a numeric value using
ra
[Link](“{0:D}”, num);
[Link](“{0:E}”, num);
w
Output
de
$456.00
co
456
4.560000E+002
The following code demonstrates the use of custom numeric format
specifiers:
using System;
class Banking
{
pg. 33
DOTNET NOTES BY ASHOK PATE
94
In Above Code,
21
The #, %, ., and 0 custom numeric format specifiers are used to
59
07
The following figure displays the example of custom numeric format
80
specifiers:
.in
ys
ra
ar
ith
w
There are some additional number format specifiers that are described in
co
pg. 34
DOTNET NOTES BY ASHOK PATE
94
21
59
07
The following figure demonstrates the conversion of a numeric value
using F, N, and X format specifiers:
80
int num = 456;
[Link](“{0:F}”, num);
[Link](“{0:N}”, num);
[Link](“{0:X}”, num);
.in
ys
Output
ra
456.00
ar
456.00
ith
1C8
w
Source Code
de
using System;
co
using [Link];
using [Link];
using [Link];
using [Link];
namespace IntroductionToCsharp
{
class Program
{
static void Main(string[] args)
{
94
syntax
//[Link]("Your Name is: {0} {1}", fname, lname); // placeholder
21
syntax
//[Link]();
}
59
}
}
07
--------------------------------------------------------------------------------------------
80
Variables & Data Types in C# .in
ys
Variables In C#
ra
de
co
pg. 36
DOTNET NOTES BY ASHOK PATE
A variable is an entity whose value can keep changing during the course
of a program.
Example
The age of a student, the address of a faculty member, and the salary
of an employee are all examples of entities that can be represented by
variables.
94
Variables
21
59
In C#, a variable is a location in the computer’s memory that is
identified by a unique name and is used to store a value. The name of
07
the variable is used to access and read the value stored in it.
Different types of data such as a character, an integer, or a string can
80
pg. 37
DOTNET NOTES BY ASHOK PATE
94
21
The following syntax is used to declare variables in C#:
59
<datatype><variableName>;
07
Where,
80
datatype: Is a valid data type in C#.
variableName: Is a valid variable name.
.in
The following syntax is used to initialize variables in C#:
ys
<variableName> = <value>;
ra
Where,
ar
ith
int empNumber;
string empName;
In Above Code,
an integer variable declares empNumber, and a string variable,
empName. Memory is allocated to hold data in each variable.
pg. 38
DOTNET NOTES BY ASHOK PATE
94
Data Types
21
Different types of values such as numbers, characters, or strings can
be stored in different variables. To identify the type of data that can
59
be stored in a variable, C# provides different data types.
07
When a variable is declared, a data type is assigned to the variable.
This allows the variable to store values of the assigned data type.
80
In C# programming language, data types are divided into two
categories: .in
1. Value Types
ys
Variables of value types store actual values that are stored in a stack
ra
The value type built-in data types are int, float, double, char, and
w
bool. User-defined value types are created using the struct and enum
de
keywords.
co
2. Reference Types
Variables of reference type store the memory address of other
variables in a heap.
These values can either belong to a built-in data type or a user-
defined data type.
Pre-defined Data Types
pg. 39
DOTNET NOTES BY ASHOK PATE
94
21
59
07
80
.in
ys
ra
Reference data types store the memory reference of other variables that
ar
hold the actual values that can be classified into the following types:
ith
Object
w
de
Object is a built-in reference data type that is a base class for all pre-
defined and user-defined data types. A class is a logical structure that
co
pg. 40
DOTNET NOTES BY ASHOK PATE
94
structure that can contain variables such as empSalary, empName,
21
and empAddress. It can also contain methods such as
CalculateSalary(), which returns the net salary of an employee.
59
Delegates
07
A delegate is a user-defined reference type that stores the reference of
80
Array
ith
ushort
int
uint
long
ulong
DataType, Its Range & Its Size
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
pg. 42
DOTNET NOTES BY ASHOK PATE
Bool keyword is used for Boolean data type which only stores TRUE or
FALSE.
Float Double And Decimal Data Type
94
21
59
07
80
String And Character Data Type
.in
String stores multiple characters in a single variable.
Double quotes will be used with string data type.
ys
Verbatim Literal
ith
Practical Example:
WITHOUT VERBATIM LITERAL: "D:\\Adil\\Csharp\\Tutorials"
– Less readable
WITH VERBATIM LITERAL: @"D:\Adil\Csharp\Tutorials" –
More readable
pg. 43
DOTNET NOTES BY ASHOK PATE
94
21
recommended at the beginning of a name.
C# is a case-sensitive language; hence, variable names count and
59
07
C# keywords cannot be used as variable names. If you still need to
use a C# keyword, prefix it with the ‘@’ symbol.
80
It is always advisable to give meaningful names to variables such that
the name gives an idea about the content that is stored in the variable.
.in
The following table displays a list of valid and invalid variable names
ys
in C#:
ra
ar
ith
w
de
co
Variable Declaration
pg. 44
DOTNET NOTES BY ASHOK PATE
In C#, you can declare multiple variables at the same time in the
same way you declare a single variable.
After declaring variables, you need to assign values to them.
Assigning a value to a variable is called initialization.
You can assign a value to a variable while declaring it or at a later
time.
94
The following is the syntax to declare and initialize a single variable:
21
<data type><variable name> = <value>;
Where,
59
07
data type: Is a valid variable type.
variable name: Is a valid variable name or identifier.
80
value: Is the value assigned to the variable.
The following is the syntax to declare multiple variables:
.in
ys
<data type><variable name1>, <variable name2>,..,<variable nameN>;
ra
Where,
ar
pg. 45
DOTNET NOTES BY ASHOK PATE
floatTest = 14.5f;
[Link](“boolTest = {0}”, boolTest);
[Link](“byteTest = ” + byteTest);
[Link](“intTest = ” + intTest);
[Link](“stringTest = ” + stringTest);
[Link](“floatTest = ” + floatTest);
In Above Code,
Variables of type bool, byte, int, string, and float are declared. Values
are assigned to each of these variables and are displayed using the
94
WriteLine() method of the Console class.
21
The code displays the following output:
59
07
80
.in
ys
ra
ar
ith
w
de
--------------------------------------------------------------------------------------------
co
pg. 46
DOTNET NOTES BY ASHOK PATE
Example: converting an int to a float will not loose any data and no exception
will be thrown, hence an implicit conversion can be done.
Where as when converting a float to an int, we loose the fractional part and
also a possibility of overflow exception. Hence, in this case an explicit
conversion is required.
For explicit conversion we can use the convert class in c#.
Parse function of int, float. Strings
94
Program:-
21
// int x = 100;
59
// float y = x; // implicit conversion of data type
07
string a = "100";
80
string b = "200";
[Link](a);
de
co
//float a = 34.657f;
//int b = (int)a; // explicit conversion of data type
//int b = Convert.ToInt32(a);
//[Link](b);
[Link]();
--------------------------------------------------------------------------------------------------------------
pg. 47
DOTNET NOTES BY ASHOK PATE
94
Consider a code that calculates the area of the circle.
To calculate the area of the circle, the value of pi and radius must be
21
59
The value of pi is a constant value.
This value will remain unchanged irrespective of the value of the
07
radius provided.
80
Similarly, constants in C# are fixed values assigned to identifiers that
are not modified throughout the execution of the code.
.in
They are defined when you want to preserve values to reuse them
later or to prevent any modification to the values.
ys
Constants In C#
ra
ar
program.
w
types.
To declare an identifier as a constant, the “const” keyword is used in
the identifier declaration. The compiler can identify constants at the
time of compilation, because of the “const” keyword.
The following syntax is used to initialize a constant:
const<data type><identifier name> = <value>;
pg. 48
DOTNET NOTES BY ASHOK PATE
where,
const: Keyword denoting that the identifier is declared as constant.
data type: Data type of constant.
identifier name: Name of the identifier that will hold the constant.
value: Fixed value that remains unchanged throughout the execution
of the code.
94
The following code declares a constant named _pi and a variable
21
named radius to calculate the area of the circle:
59
const float _pi = 3.14F;
float radius = 5;
float area = _pi * radius * radius;
07
[Link](“Area of the circle is ” + area);
80
In Above Code,
A constant called _pi is assigned the value 3.14, which is a fixed
.in
value. The variable, radius, stores the radius of the circle. The code
ys
calculates the area of the circle and displays it as the output.
ra
Literals In C# Programming
ar
ith
Example
For example, in the following declaration,
string bookName = “Csharp”
Boolean Literal
Integer Literal
Real Literal
Character Literal
String Literal
Null Literal
94
Boolean Literal
21
Boolean Literal: Boolean literals have two values, true or false. For
example,
59
o bool val = true;
07
where,
o true: Is a Boolean literal assigned to the variable val.
80
Integer Literal
.in
Integer Literal: An integer literal can be assigned to int, uint, long, or
ys
ulongdata types. Suffixes for integer literals include U, L, UL, or LU.
U denotes uint or ulong, L denotes long. UL and LU denote ulong.
ra
For example,
ar
Where,
w
Real Literal
co
Where,
pg. 50
DOTNET NOTES BY ASHOK PATE
Where,
94
21
String Literal
59
String Literal: There are two types of string literals in C#, regular and
07
verbatim. A regular string literal is a standard string. A verbatim
string literal is similar to a regular string literal but is prefixed by the
80
‘@’ character. A string literal is always enclosed in double quotes.
For example, .in
o string mailDomain = “@[Link]”;
ys
Where,
o @[Link]: Is a verbatim string literal.
ra
ar
Null Literal
ith
Null Literal: The null literal has only one value, null. For example,
w
Where,
o null: Specifies that e-mail does not refer to any objects
co
(reference).
--------------------------------------------------------------------------------------------
pg. 51
DOTNET NOTES BY ASHOK PATE
94
format.
If you are displaying GMT time as the output, you can display the
21
GMT time along with the abbreviation GMT using date and time
59
format specifiers.
The date and time format specifiers allow you to display the date and
07
80
The following is the syntax for date and time format specifiers:
[Link](“{format specifier}”, <datetime object>);
.in
Where,
ys
D Long date
f Full date/time (short time)
de
Syntax
DateTime dt = [Link];
[Link]("{0:D}", dt);
[Link]("{0:f}", dt);
[Link]("{0:F}", dt);
pg. 52
DOTNET NOTES BY ASHOK PATE
[Link]("{0:g}", dt);
[Link]("{0:d} {1:D}", dt, dt);
Time Formats
Format Specifier Name
G General date/time (long time)
m or M Month day
t Short time
94
T Long time
y or Y Year month pattern
21
ddd Represents the abbreviated name of the day of the week.
dddd Represents the full name of the day of the week.
59
FF Represents the two digits of the seconds fraction
HH Represents the hour from 00 to 23
07
MM Represents the month as a number from 01 to 12
MMM Represents the abbreviated name of the month
80
ss •Represents the seconds as a number from 0 to 59
[Link]("{0:dd-MM-yyyy}", dt);
ra
DateTimedt = [Link];
// Returns short date (MM/DD/YYYY)
co
Output
pg. 53
DOTNET NOTES BY ASHOK PATE
94
time using the G, m, t, T, and y date and time format specifiers:
21
DateTimedt = [Link];
// Returns short date and short time with seconds
[Link](“Short date and short time with seconds (G):{0:G}”, dt);
59
// Returns month and day - M can also be used
[Link](“Month and day (m):{0:m}”, dt);
// Returns short time
07
[Link](“Short time (t):{0:t}”, dt);
// Returns short time with seconds
[Link](“Short time with seconds (T):{0:T}”, dt);
80
// Returns year and month - Y also can be used
[Link](“Year and Month (y):{0:y}”, dt);
Output .in
ys
Short date and short time with seconds (G):23/04/2007 [Link] PM
Month and day (m):April 23
ra
pg. 54
DOTNET NOTES BY ASHOK PATE
94
21
59
The following code demonstrates the use of custom DateTime format
07
specifiers:
80
using System;
class DateTimeFormat
{
public static void Main(string[] args)
{
DateTime date = [Link];
.in
[Link]("Date is {0:ddd MMM dd, yyyy}", date);
ys
[Link]("Time is {0:hh:mm tt}", date);
[Link]("24 hour time is {0:HH:mm}", date);
ra
In Above Code,
de
The date and time is displayed using the different DateTime format
co
specifiers.
The following figure displays the output of the code:
--------------------------------------------------------------------------------------------
pg. 55
DOTNET NOTES BY ASHOK PATE
94
• Is referred to as a decision-making construct.
21
• Allow you to take logical decisions about executing different
59
blocks of a program to achieve the required logical output.
07
• C# supports the following decision-making constructs:
80
• if…else
• if…else…if .in
• Nested if
ys
ra
• switch…case
ar
The If Statement
w
de
pg. 56
DOTNET NOTES BY ASHOK PATE
94
21
59
07
80
.in
The If-else Statement
ys
ra
block and the else block starts with the else keyword followed by
de
a block of statements.
co
94
evaluates to false, the condition specified in the following else…if
statement is evaluated.
21
Nested If Construct
59
07
• The nested if construct consists of multiple if statements.
80
• The nested if construct starts with the if statement, which is
called the outer if statement, and contains multiple if
.in
statements, which are called inner if statements.
ys
• In the nested if construct, the outer if condition controls the
ra
is true.
w
Switch…case Construct
• A program is difficult to comprehend when there are too many if
statements representing multiple selection constructs.
• To avoid using multiple if statements, in certain cases, the
switch…case approach can be used as an alternative.
pg. 58
DOTNET NOTES BY ASHOK PATE
94
• In C#, the flow of execution from one case statement is not
allowed to continue to the next case statement and is referred to
21
as the ‘no-fall-through’ rule of C#.
59
Nested-switch…case Construct
07
• C# allows the switch…case construct to be nested. That is, a case
80
block of a switch…case construct can contain another switch…
case construct. .in
ys
• Also, the case constants of the inner switch…case construct can
have values that are identical to the case constants of the outer
ra
construct.
ar
ith
--------------------------------------------------------------------------------------------
w
Arithmetic Operators
de
94
• >
21
• <
59
• >=
07
• <=
80
Logical OR CONDITIONAL Operators
.in
ys
ra
ar
ith
w
de
co
pg. 60
BUILT IN DATA TYPES IN C#
INTEGRAL TYPE
o Signed Integers (Which Takes Negative And Positive Values)
o Unsigned Integers (Which Only Takes Positive Values)
sbyte
byte
short
ushort
int
uint
long
94
ulong
21
59
07
80
.in
ys
ra
ar
ith
w
de
MINVALUE PROPERTY
MAXVALUE PROPERTY
co
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
String And Character Data Type
String stores multiple characters in a single variable.
Double quotes will be used with string data type.
Char stores single character at a time in a variable.
Single quotes will be used for char data type.
ESCAPE SEQUENCE
Verbatim Literal
o Verbatim literal is a string with an @ symbol.
94
o Verbatim literal make escape sequences translate as normal printable
characters to enhance readability.
21
Practical Example:
59
WITHOUT VERBATIM LITERAL: "D:\\Adil\\Csharp\\Tutorials" – Less readable
07
WITH VERBATIM LITERAL: @"D:\Adil\Csharp\Tutorials" – More readable
80
.in
ys
ra
ar
ith
w
de
co
Data types conversion in c# programming
There are two types of conversions implicit and explicit conversion.
Implicit conversion is done by the compiler.
1. When there is no loss of information if the conversion is done.
2. If there is no possibility of throwing exception during the conversion.
Example: converting an int to a float will not loose any data and no exception will
be thrown, hence an implicit conversion can be done.
Where as when converting a float to an int, we loose the fractional part and also a
94
possibility of overflow exception. Hence, in this case an explicit conversion is
required.
21
For explicit conversion we can use the convert class in c#.
59
Parse function of int, float. Strings
07
80
.in
ys
ra
ar
ith
w
de
co
Value Type Vs Reference Type In C#
struct Employee
STACK HEAP
{
public int Salary; class Employee
{
STACK HEAP
public int Age;
} public int Salary;
class Program public int Age;
{ }
static void Main(string[] args)class Program
{ {
Employee e = new Employee(); static void Main(string[] args)
{
94
[Link] = 5000;
Salary Age Salary Age
[Link] = 23; Employee
e2 e = new Employee();
[Link] =5000
5000; 23 5000 25
21
Employee e1 = e; [Link] = 23;
Employee e2 = e; Salary Age
59
e1Employee e1 = e;
[Link] = 25;
5000= e; 23
[Link]([Link]); Employee e20x3453
07
[Link]([Link]); [Link] = 25;
[Link](); [Link]([Link]);
Salary
0x3453Age
80
e [Link]([Link]);
}
} 5000 25
[Link]();
}
} 0x3453 .in
e2
ys
e1
e
ra
ar
ith
w
de
VALUE TYPE:
co
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.
The following data types are all of value type:
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
94
stores the address where the value is being stored. In other words, a reference
21
type contains a pointer to another memory location that holds the data.
59
The following data types are of reference type:
String
07
All arrays, even if their elements are value types
80
Class
object
Delegates
Interface
.in
ys
ra
ar
ith
w
They are stored on stack memory They are stored on heap memory
Contains actual value Contains reference to a value
Cannot contain null values. However this can Can contain null values.
be achieved by nullable types
Memory is allocated at compile time Memory is allocated at run time
Stack Heap
Values are stored on one another like a Values are stored in random order like
stack. dumped into a huge space
Used for value type Used for reference types
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
Var And Dynamic Keywords In C#
Var Keyword:
Var was introduced in c# 3.0.
Var keyword is used to store any type of data in its variable.
Value of var variable is decided at compile time.
We have to initialize the variable with var keyword.
If we want to check the type of value which is stored in var variable then we
can use gettype() method with the var variable.
When we initialize the var variable with some value then we cannot change
94
the value of var variable with some other data type value.
We can use all the methods of particular type value which is stored in var
21
variable.
Intellisense help is available for the var type of variables. This is because, its
59
type is inferred by the compiler from the type of value it is assigned and as
07
a result, the compiler has all the information related to the type.
Var variables cannot be used for property or return values from a function.
80
They can only be used as local variable in a function.
We cannot use var variable as a function parameter.
Var keyword is of value type. .in
Dynamic Keyword:
ys
Dynamic keyword is also used to store any type of data in its variable.
ar
change the value of dynamic variable with some other data type value.
Intellisense help is not available for dynamic type of variables since their
type is unknown until run time. So intellisense help is not available.
Dynamic variables can be used to create properties and return values from
a function.
We can use dynamic variable as a function parameter.
Dynamic keyword is of reference type.
BOXING AND UN-BOXING IN C#
As we all know, C# is a strongly-typed language. That means we have to declare the type of a
variable that indicates the kind of values it is going to store, such as integer, double, float,
boolean decimal, text, etc.
In C#, data types are categorized into two types: Value types and Reference types. Value types
include simple types (such as int, double, float, bool, and char), enum types, struct types, and
Nullable value types. Reference types include class types, interface types, delegate types, and
array types.
94
In C#, Boxing and unboxing allows developers to convert .NET data types from value type to
reference type and vice versa.
21
In C#, Converting a value type to a reference type is called called boxing in C# and converting
a reference type to a value type is called unboxing in C#.
Mainly C# has two kinds of data types, value types and reference types. Value type stores the
59
value itself, on the other hand reference type stores the address of the value where it is stored.
07
In C#, Some predefined data types such as int, float, double, decimal, bool, char, etc. are value
types and object, string, and array are reference types.
80
What Is Boxing In C# ?
.in
Implicit (automatic) conversion of a value type to a reference type is called "Boxing".
ys
Example:
ra
In Boxing process, a value type is being allocated on the heap rather than the stack.
ith
w
de
co
What Is Un-Boxing In C# ?
Explicit (manual) conversion of the same reference type (which is being created by
boxing), back to a value type.
Example:
int num1 = 10; // int is value type
object obj1 = num1; // Implicit conversion of value type into reference type
(Boxing)
94
int num2 = (int) obj1; // Explicit conversion of reference type into value
type (Unboxing)
21
In unboxing process, an unboxed value is being allocated to a variable on the stack rather
than the heap.
59
07
80
.in
ys
ra
ar
ith
w
de
co
Pass By Value And Pass By Reference In C#
(Ref And Out Keywords)
PASS BY VALUE
5
94
PassByValue(value); 15 [Link](“value is: ” + a);
21
[Link](value); }
59
}
07
80
PASS BY REFERENCE
{ a = a + 10;
ra
15
ar
abc
[Link](“value is: ” + a);
int value = 5;
ith
}
PassByRef(ref value);15
w
de
[Link](value);
co
}
PASS BY OUT
{ {
[Link](value); }
94
}
21
59
Pass By Reference (Ref Keyword)
07
The ref keyword causes arguments to be passed in a method by reference.
In call by reference, the called method changes the value of the parameters
80
passed to it from the calling method.
Any changes made to the parameters in the called method will be reflected
.in
in the parameters passed from the calling method when control passes
back to the calling method.
ys
It is necessary that both the called method and the calling method must
ra
initialized.
ith
Out Keyword
w
The out keyword is similar to the ref keyword and causes arguments to be
de
passed by reference.
co
The only difference between the two is that the out keyword does not
require the variables that are passed by reference to be initialized.
Both the called method and the calling method must explicitly use the out
keyword.
Pass By Value
94
Pass By Value
21
Pass By Reference (Ref Keyword)
59
The ref keyword causes arguments to be passed in a method
by reference.
07
In call by reference, the called method changes the value of
80
the parameters passed to it from the calling method.
Any changes made to the parameters in the called method
will be reflected in the parameters passed from the calling
.in
method when control passes back to the calling method.
ys
It is necessary that both the called method and the calling
method must explicitly specify the ref keyword before the
ra
required parameters.
ar
Pass By Reference
ar
{
// actions to be performed
}
co
where,
parameter 1…parameterN: Specifies that there can be any
number of parameters and it is not necessary for all the parameters
to be ref parameters.
using System;
class RefParameters
{
static void Calculate(ref intnumValueOne, ref int
numValueTwo)
{
numValueOne = numValueOne * 2;
numValueTwo = numValueTwo / 2;
]
}
static void Main(string[] args)
{
intnumOne = 10;
intnumTwo = 20;
[Link](“Value of Num1 and Num2 before calling method “ +numOne + “,
“ + numTwo);
Calculate(ref numOne, ref numTwo);
[Link](“Value of Num1 and Num2 after calling method “ +numOne + “,
“ + numTwo);
94
}
}
21
In Above Code,
59
The Calculate() method is called from the Main() method,
07
which takes the parameters prefixed with the ref keyword.
The same keyword is also used in the Calculate() method
80
Calculate().
w
de
94
21
59
07
80
Out Keyword C# .in
ys
The following syntax is used to pass values by reference
using the out keyword:
ra
ar
// actions to be performed
}
w
where,
de
94
}
}
21
In Above Code,
59
the Depreciation() method is invoked from the Main()
07
method passing the val parameter using the out keyword. In
the Depreciation() method, the depreciation is calculated and
80
the resultant depreciated amount is deducted from the val
variable. The final value in the amt variable is displayed as
the output.
.in
ys
The following figure shows the use of out keyword:
ra
ar
ith
w
de
co
namespace REF_AND_OUT_KEYWORDS
{
class Program
{
//public static void PassByValue(int a)
//{
// a = a + 10;
// [Link]("Value is: {0}", a);
//}
94
public static void PassByOut(out int a)
{
21
a = 20;
[Link]("Value is: {0}", a);
59
}
07
{
int value;
PassByOut(out value); // 20
80
[Link](value); // 20
[Link]();
}
}
} .in
ys
ra
ar
ith
w
de
co
Access Modifiers In C# Programming
Access Modifiers
C# provides you with access modifiers that allow you to specify
which classes can access the data members of a particular class.
In C#, there are four commonly used access modifiers.
94
21
59
07
80
These are described as follows:
.in
ys
public: The public access modifier provides the most permissive
ra
access level.
The members declared as public can be accessed anywhere in the
ar
class Employee
{
// No access restrictions.
public string Name = “Adil”;
}
private: The private access modifier provides the least permissive
access level. Private members are accessible only within the class
in which they are declared.
Following code declares a variable called _salary as private,
which means it cannot be accessed by any other class except for
the Employee class.
94
class Employee
{
21
// Accessible only within the class
private float _salary;
}
59
protected:
07
The protected access modifier allows the class members to be
accessible within the class as well as within the derived classes.
80
The following code declares a variable called Salary as protected,
.in
which means it can be accessed only by the Employee class and
its derived classes:
ys
class Employee
ra
{
// Protected access
ar
94
21
59
07
80
.in
ys
ra
ar
80
The following syntax declares a protected variable:
protected <data_type> <VariableName>;
.in
where,
ys
data_type: Is the data type of the data member.
ra
where,
de
94
}
21
In Above code:
59
Two variables are created in the class Animal with the
protected keyword.
07
The class Cat is inherited from the class Animal.
80
The instance of the class Cat is created that is referring the
two variables defined in the class Animal using the dot (.)
operator. .in
The protected access modifier allows the variables declared
ys
in the class Animal to be accessed by the derived class Cat.
ra
Output
ar
94
They are automatically executed whenever an instance of a
21
class is created.
A constructor has exactly the same name as that of class and
59
07
A C# class can contain one or more special member
functions having the same name as the class, called
80
constructors.
A constructor is a method having the same name as that of
the class.
.in
ys
The following figure shows the constructor declaration:
ra
ar
ith
w
de
co
94
21
59
07
80
.in
ys
an instance of a class.
protected: Specifies that the base class will initialize on its
own whenever its derived classes are created. Here, the class
object can only be created in the derived classes.
internal: Specifies that the constructor has its access limited
to the current assembly. It cannot be accessed outside the
assembly.
The following code creates a class Circle with a private
constructor:
using System;
public class Circle
{
private Circle()
{
}
}
class CircleDetails
94
{
public static void Main(string[] args)
{
21
Circle objCircle = new Circle();
}
59
}
In Above Code,
07
The program will generate a compile-time error because an
80
This means no other class can use the data members of the
ar
name.
co
94
_empAge, and _deptName with the help of a constructor:
21
using System;
59
class Employees
{
07
string _empName;
int _empAge;
string _deptName;
80
Employees(string name, intnum)
{
_empName = name;
_empAge = num;
_deptName = “Research & Development”;
}
.in
static void Main(string[] args)
ys
{
Employees objEmp = new Employees(“John”, 10);
ra
[Link](objEmp._deptName);
}
}
ar
ith
In Above Code,
w
namespace ConstructorsInCsharp
{
class Employees
{
int EmpId;
string EmpName;
int EmpAge;
94
public Employees(int EmpId, string EmpName, int EmpAge)
21
{
[Link] = EmpId;
[Link] = EmpName;
59
[Link] = EmpAge;
}
07
public int getId()
{
return [Link];
80
}
public string getName()
{
return [Link];
}
public int getAge()
.in
{
ys
return [Link];
}
ra
[Link]("Employee Id is {0}",[Link]());
[Link]("Employee Name is {0}", [Link]());
w
[Link]();
}
}
}
TYPES OF CONSTRUCTORS IN C#
Constructors generally following types:
Default Constructor
Parameterized constructor
Private Constructor
Static Constructor
Copy Constructor
STATIC CONSTRUCTOR
94
A static constructor is used to initialize static variables of the class
21
and to perform a particular action only once.
59
Static constructor is called only once, no matter how many objects
you create.
07
Static constructor is called before instance constructor.
80
A static constructor does not take any parameters and does not
use any access modifiers.
Key points of static constructor .in
ys
Only one static constructor can be created in the class.
It is called automatically before the first instance of the class
ra
created.
ar
94
without any parameters is called default constructor. It initializes the
21
same value of every instance of class.
59
Parameterized Constructor
07
A constructor which has at least one parameter is called Parameterized
Constructor. Using this type of constructor we can initialize each
80
instance of the class to different values.
.in
ys
ra
ar
ith
w
de
co
COPY CONSTRUCTOR IN C#
The constructor which creates an object by copying variables from
another object is called a copy constructor. The purpose of a copy
constructor is to initialize a new instance to the values of an existing
instance.
94
existing instance.
21
In simple words, we can say copy constructor is a constructor which
59
copies a data of one object into another object.
07
80
.in
ys
ra
ar
ith
w
de
co
Private Constructor In C#
When a constructor is created with a private specifier, it is not possible
for other classes to derive from this class, neither is it possible to create
an instance of this class. They are usually used in classes that contain
static members only. Some key points of a private constructor are:
94
any, the compiler will not add the parameter-less public
21
constructor to the class.
In the presence of parameterless private constructor you cannot
59
create a default constructor.
07
We cannot inherit the class in which we have a private
constructor.
80
We can have parameters in private constructor. YES
.in
ys
ra
ar
ith
w
de
co
Destructors In C# Programming
A destructor is a special method which has the same name as the class
but starts with the character ~ before the class name and immediately
de-allocates memory of objects that are no longer required.
Following are the features of destructors:
Destructors cannot be overloaded or inherited.
Destructors cannot be explicitly invoked.
Destructors cannot specify access modifiers and cannot take
94
parameters.
21
A destructor is a special method which has the same name as the
class but starts with the character ~ before the class name and
59
immediately de-allocates memory of objects that are no longer
07
required.
80
A C# class can also have a destructor (only one is allowed per
class), which is a special method and also has the same name as
the class but prefixed with a special symbol ~.
.in
ys
A destructor of an object is executed when the object is no longer
required in order to de-allocate memory of the object.
ra
ar
class Employee
{
privateint _empId;
private string _empName;
privateint _age;
private double _salary;
Employee(int id, string name, int age, double sal)
{
[Link](“Constructor for Employee called”);
_empId = id;
_empName = name;
_age = age;
_salary = sal;
}
~Employee()
using System;
class Employee
{
privateint _empId;
private string _empName;
privateint _age;
94
private double _salary;
Employee(int id, string name, int age, double sal)
{
21
[Link](“Constructor for Employee called”);
59
}
static void Main(string[] args)
{
07
Employee objEmp = new Employee(1, “John”, 45, 35000);
[Link](“Employee ID: “ + objEmp._empId);
[Link](“Employee Name: “ + objEmp._empName);
80
[Link](“Age: “ + objEmp._age);
[Link](“Salary: “ + objEmp._salary);
}
}
.in
ys
In Above Code,
ra
going to be executed.
co
namespace DESTRUCTORS
{
class person
{
public string Name;
public int Age;
94
return [Link];
}
21
~person()
{
59
[Link]("Destructor has been invoked !!");
}
07
}
class Program
{
80
static void Main(string[] args)
{
person Ali = new person("Ali",22);
person Anas = new person("Anas", 23);
[Link]([Link]());
[Link]([Link]());
.in
[Link]("--------------");
ys
[Link]([Link]());
[Link]([Link]());
ra
//[Link]();
ar
}
}
ith
}
w
de
co
TYPES OF DELEGATES IN C#
MULTIPLE DELEGATES
SINGLE CAST DELEGATES
MULTI CAST DELEGATES
1. MULTIPLE DELEGATES:
In C#, a user can invoke multiple delegates within a single program.
94
Depending on the delegate name or the type of parameters passed
to the delegate, the appropriate delegate is invoked.
21
59
07
2. SINGLE CAST DELEGATES:
80
Singlecast delegate point to single method at a time. In this the
delegate is assigned to a single method at a time. They are derived from
.in
[Link] class
ys
ra
When a delegate is wrapped with more than one method that is known
ith
as a multicast delegate.
w
In C#, delegates are multicast, which means that they can point to more
de
[Link] class.
We can use += and -= assignment operators to implement multi cast
delegates.
What Are Properties In C#
Properties allow you to control the accessibility of a class variables, and are the
recommended way to access variables from the outside in c#.
A property is much like a combination of a variable and a method - it can't take any
parameters, but you are able to process the value before it's assigned to our returned.
Properties are like data fields (variables), but have logic behind them.
94
From the outside, they look like any other member variable.
21
o But they act like a member function.
59
Defined like a field, with “get” and “set” accessors code added.
07
Properties are also used for encapsulation.
80
Types Of Properties In C#
Read / write properties .in
ys
Read only properties
Write only properties
ra
94
manner.
A property is much like a combination of a variable and a
21
method - it can't take any parameters, but you are able to
process the value before it's assigned to our returned.
59
Properties are like data fields (variables), but have logic
07
behind them.
From the outside, they look like any other member
80
variable.
o But they act like a member function.
.in
Defined like a field, with “get” and “set” accessors code
ys
added.
Properties are also used for encapsulation.
ra
ar
Example
ith
Properties:
Properties allow to protect a field in the class by reading
and writing to the field through a property declaration.
Properties allow to access private fields, which would
otherwise be inaccessible.
Properties can validate values before allowing you to
change them and also perform specified actions on those
changes.
Properties ensure security of private data.
Properties support abstraction and encapsulation by
exposing only necessary actions and hiding their
implementation.
94
Types Of Properties In C#
21
Read / write properties
59
07
Write only properties
Auto implemented properties
80
The following syntax is used to declare a property in C#.
<access_modifier><return_type><PropertyName>
.in
{
ys
//body of the property
}
ra
where,
ar
internal.
de
return.
PropertyName: Is the name of the property.
Get And Set Accessors
Property accessors allow you to read and assign a value to a
field by implementing get and set accessors as follows:
The Get Accessor
The get accessor is used to read a value and is executed
when the property name is referred.
It does not take any parameter and returns a value that is of
the return type of the property.
The Set Accessor
94
The set accessor is used to assign a value and is executed
21
59
to (=) operator.
This value is stored in the private field by an implicit
07
80
accessor.
Syntax .in
<access_modifier><return_type>PropertyName>
ys
{
get
ra
{
// return value
ar
}
set
{
ith
// assign value
}
w
}
de
The following code demonstrates the use of the get and set
accessors.
co
using System;
class SalaryDetails
{
private string _empName;
public string EmployeeName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
static void Main (string [] args)
{
SalaryDetails objSal = new SalaryDetails();
[Link] = “Patrick Johnson”;
[Link](“Employee Name: “ + [Link]);
}
}
94
In Above Code,
21
The class SalaryDetails creates a private variable
59
_empName and declares a property called EmployeeName.
The instance of the SalaryDetails class, objSal, invokes the
07
80
initialize the value of employee name. This invokes the set
accessor, where the value keyword assigns the value to
_empName. .in
The code displays the employee name by invoking the
ys
property name.
ra
Output
w
de
Read-Only Property
The read-only property allows you to retrieve the value of a
private field. To create a read-only property, you should define
the get accessor.
The following syntax creates a read-only property.
<access_modifier><return_type><PropertyName>{
get
{
// return value
}
}
94
21
using System;
class Books {
string _bookName;
59
long _bookID;
public Books(string name, int value){
_bookName = name;
07
_bookID = value;
}
public string BookName {
80
get{ return _bookName; }
}
public long BookID {
get { return _bookID; }
}
}
.in
ys
class BookStore {
static void Main(string[] args) {
Books objBook = new Books("Learn C# in 21 Days", 10015);
ra
}
}
ith
In Above Code,
w
de
94
private field.
To create a write-only property, you should define the set
21
accessor.
59
The following syntax creates a write-only property.
07
<access_modifer><return_type><PropertyName>
80
{
set
{
// assign value
}
}
.in
ys
The following code demonstrates how to create a write-only
ra
property.
ar
using System;
class Department {
ith
string _deptName;
int _deptID;
w
}
public intDeptID {
set { _deptID = value; }
co
}
public void Display() {
[Link]("Department Name: " + _deptName);
[Link]("Department ID: " + _deptID);
}
}
class Company {
static void Main(string[] args) {
Department objDepartment = new Department();
[Link] = 201;
[Link] = "Sales";
[Link]();
}
}
In Above Code,
The Department class consists of two write-only properties.
The Main() method of the class Company instantiates the
class Department and this instance invokes the set accessor
94
of the appropriate write-only properties to assign the
department name and its ID.
21
The Display() method of the class Department displays the
59
name and ID of the department.
07
Output
80
Department Name: Sales
Department ID: 201
.in
Read-Write Property
ys
<access_modifer><return type><PropertyName>
{
get
co
{
// return value
}
set
{
// assign value
}
}
The following code demonstrates how to create a read-write
property.
using System;
class Product {
string _productName;
int _productID;
float _price;
public Product(string name, intval) {
_productName = name;
_productID = val;
94
}
public float Price {
get { return _price;}
21
set { if (value < 0) { _price = 0; }
else { _price = value; }
59
}
}
public void Display() {
07
[Link]("Product Name: " + _productName);
[Link]("Product ID: " + _productID);
[Link]("Price: " + _price + "$");
80
}
}
class Goods {
static void Main(string[] args) {
.in
Product objProduct = new Product(“Hard Disk”, 101);
[Link] = 345.25F;
[Link]();
ys
}
}
ra
In Above Code,
ar
ith
statement.
de
Static Properties
94
21
The static property is used to access and manipulate static
fields of a class in a safe manner.
59
The static property declared by using the static keyword.
07
The static property accessed using the class name and thus,
belongs to the class rather than just an instance of the class.
80
The static property called by a programmer without
creating an instance of the class. .in
We cannot initialize instance fields within static property.
The static property accessed using the class name and thus,
ys
using System;
class University
{
private static string _department;
private static string _universityName;
public static string Department
{
get
{
return _department;
}
set
{
_department = value;
}
}
public static string UniversityName
{
get { return _universityName; }
set { _universityName = value; }
}
}
class Physics
94
{
static void Main(string[] args)
21
{
[Link] = "University of Maryland";
[Link] = "Physics";
59
[Link]("University Name: " + [Link]);
[Link]("Department name: " + [Link]);
}
07
}
In Above Code,
80
The class University defines two static properties
.in
UniversityName and DepartmentName.
The Main() method of the class Physics invokes the static
ys
properties.
co
Output
University Name: University of Maryland
Department name: Physics
Abstract Properties
The word Abstract means incomplete, which means no
implementation in programming.
This is a duty of child class to implement an abstract
member of their parent class.
Abstract property declared by using the abstract keyword.
Abstract properties contain only the declaration of the
property without the body of the get and set accessors
94
(which do not contain any statements and can be
implemented in the derived class).
21
Abstract properties are only allowed in an abstract class.
59
Abstract Properties are used:
07
when it is required to secure data within multiple fields of
80
the derived class of the abstract class.
to avoid redefining properties by reusing the existing
properties.
.in
ys
The following code demonstrates a class that uses an
ra
abstract property.
ar
using System;
public abstract class Figure {
ith
}
public abstract float DimensionTwo {
de
set; }
}
class Rectangle : Figure {
co
float _dimensionOne;
float _dimensionTwo;
public override float DimensionOne {
set {
if (value <= 0){
_dimensionOne = 0;
}
else {
_dimensionOne = value;
}
}
}
public override float DimensionTwo {
set {
if (value <= 0)
{
_dimensionTwo = 0;
}
else {
_dimensionTwo = value;
}
}
}
float Area() {
94
return _dimensionOne * _dimensionTwo;
}
21
static void Main(string[] args) {
Rectangle objRectangle = new Rectangle();
[Link] = 20;
59
[Link] = 4.233F;
[Link]("Area of Rectangle: " + [Link]());
}
07
}
80
In Above Code,
The abstract class Figure declares two write-only abstract
.in
properties, DimensionOne and DimensionTwo.
ys
The class Rectangle inherits the abstract class Figure and
ra
the rectangle.
ith
Rectangle.
This instance invokes the properties, DimensionOne and
co
94
Unlike other properties, the boolean property produces only
true or false values.
21
While working with boolean property, a programmer needs
59
to be sure that the get accessor returns the boolean value.
07
Source Code Of Properties
80
using System;
using [Link];
using [Link];
using [Link]; .in
using [Link];
ys
namespace PROPERTIES
{
class Student
ra
{
public string firstName { get; private set; }
ar
lastName = lname;
}
de
}
co
class Program
{
static void Main(string[] args)
{
Student s = new Student("Adil","Mehmood");
[Link]([Link]);
[Link]([Link]);
//[Link] = 23;
//[Link] = "Adil";
//[Link] = "Mehmood";
//[Link]([Link]);
//[Link]([Link]);
//[Link]([Link]);
[Link]();
}
}
}
94
using System;
using [Link];
using [Link];
21
using [Link];
using [Link];
59
namespace Abstract_Properties
{
abstract class person
07
{
public abstract uint Id { get; set; }
public abstract string Name { get; set; }
80
}
set
{
ar
if (value == 0)
{
ith
{
[Link] = value;
de
}
co
}
get
{
return [Link];
}
}
get
{
return [Link];
94
}
21
}
}
59
class Program
{
static void Main(string[] args)
07
{
student Anas = new student();
80
[Link] = 22;
[Link] = "Anas Qureshi";
[Link]([Link]);
[Link]([Link]);
[Link](); .in
}
}
ys
}
ra
using System;
using [Link];
ith
using [Link];
using [Link];
w
using [Link];
de
namespace STATIC_PROPERTY
{
class university
co
{
private static string UniversityName;
private static string DepartmentName;
get
{
return UniversityName;
}
94
}
21
public static string _DepartmentName {
set
59
{
if([Link](value))
07
{
[Link]("You are not allowed to insert null or
empty value in department Name !!");
80
}
else
{
DepartmentName = value;
}
} .in
get
ys
{
return DepartmentName;
}
ra
}
ar
}
ith
class Program
{
w
{0}",university._UniversityName);
[Link]("University Department Name is: {0}",
university._DepartmentName);
[Link]();
}
}
}
STATIC PROPERTY IN C#
The static property is used to access and manipulate static fields
of a class in a safe manner.
The static property declared by using the static keyword.
The static property accessed using the class name and thus,
belongs to the class rather than just an instance of the class.
The static property called by a programmer without creating an
instance of the class.
We cannot initialize instance fields within static property.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
STATIC CONSTRUCTOR IN C#
A static constructor is used to initialize static variables of the class
and to perform a particular action only once.
Static constructor is called only once, no matter how many objects
you create.
Static constructor is called before instance (default or
parameterized) constructor.
A static constructor does not take any parameters and does not
94
use any access modifiers.
21
KEY POINTS OF STATIC CONSTRUCTOR
Only one static constructor can be created in the class.
59
It is called automatically before the first instance of the class
07
created.
80
We cannot call static constructor directly. CLR (COMMON
LANGUAGE RUNTIME)
.in
ys
ra
ar
ith
w
de
co
STATIC AND INSTANCE MEMBERS OF CLASS IN C#
Instance Member:
Instance member have a separate copy for each and every object
of the class.
Instance member belongs to the objects of the class.
When no static keyword is present the class member is called
non-static or instance member.
Instance or non-static members are invoked using objects of the
class.
94
"this" keyword is used with instance members not with static
21
members.
Instance means "Example", so object have different names in
59
programming like instance and example.
07
Every Object have
separate 2 Variables
3 Objects namely
80
Umar, Ali, Zain Int rollNo;
2 Instance Variables
Ali
String name;
ar
ith
Zain
Int rollNo;
w
de
String name;
co
Static Member:
Static member belongs to the class.
We can define class members as static using the static keyword.
When we declare a member of a class as static, it means no
matter how many objects of the class are created, there is only
94
one copy of the static member.
Static variables are used for defining constants because their
21
values can be retrieved by invoking the class without creating an
59
instance of it.
Static variables can be initialized outside the member function or
07
class definition.
80
You can also initialize static variables inside the class definition.
You can also declare a member function as static.
.in
Such functions can access only static variables.
Static member are invoked using class name.
ys
ra
String SchoolName;
Ali
de
co
Zain
94
21
common array name.
An array simplifies the task of maintaining these values
59
07
Each value is referred to as an element.
80
These elements are accessed using subscripts or index
numbers that determine the position of the element in the
array list. .in
C# supports zero-based index values in an array.
ys
This means that the first array element has an index number
ra
zero while the last element has an index number n-1, where n
ar
data, easy sorting of data, and easy tracking of the data length.
w
de
co
Declaring Arrays
Arrays are reference type variables whose creation involves two
steps:
Declaration
94
21
location.
59
Memory allocation:
07
Declaring an array does not allocate memory to the array.
80
Following is the syntax for declaring an array:
data_type[] arrayName;
.in
ys
In Above syntax:
ra
ar
de
Initializing Arrays
co
The new keyword allocates memory to the array and values can
94
then be assigned to the array.
21
If the elements are not explicitly assigned, default values are
stored in the array.
59
07
The following table lists the default values for some of the
widely used data types:
80
DATA TYPES DEFAULT VALUES
int
.in 0
ys
float 0.0
ra
double 0.0
ar
char '\0'
ith
string Null
w
de
In Above Syntax,
size-value: Specifies the number of elements in the array. You
can specify a variable of type int that stores the size of the array
instead of directly specifying a value.
94
public int[] number = new int[5];
21
number[0] = 11;
number[1] = 22;
number[2] = 33;
59
number[3] = 44;
number[4] = 55;
07
The following syntax is used to create and initialize an array
80
without using the new keyword:
.in
type[] arrayIdentifier = {val1, val2, val3, ..., valN};
ys
In Above Syntax,
ra
ar
w
Example:
de
94
Source Code - Example 1
21
using System;
59
using [Link];
07
using [Link];
using [Link];
80
using [Link];
namespace ArraysDemo
.in
ys
{
ra
class Program
ar
{
ith
{
w
de
//[Link]([Link]);
//{
// [Link](myArray[i]);
//}
//foreach (string name in myArray)
//{
// [Link](name);
94
//}
21
//[Link]("Foreach Loop Ends..");
59
07
//int[] myArray = new int[] { 10,20,30,40 };
80
//int[] myArray = new int[4];
//myArray[0] = 10;
.in
ys
//myArray[1] = 20;
ra
//myArray[2] = 30;
ar
//myArray[3] = 40;
ith
//[Link](myArray[0]);
w
//[Link](myArray[1]);
de
//[Link](myArray[2]);
co
//[Link](myArray[3]);
[Link]();
}
Source Code - Example 2
using System;
using [Link];
94
using [Link];
21
using [Link];
using [Link];
59
07
namespace Arrays_Demo
80
{
class Program
{ .in
static void Main(string[] args)
ys
{
ra
ar
names[i] = name;
}
[Link]("----------------");
94
{
[Link](name);
21
}
59
//string[] names = new string[] {"Adil","Ali","Anas","Amir" };
07
80
//string[] names = {"Adil", "Zubia", "Anum", "Farah","Abdul
Rehman","Sameed","Ammad" };
.in
//foreach(string i in names)
ys
//{
ra
// [Link](i);
ar
//}
ith
w
//{
co
// [Link](names[i]);
//}
// 2 types of arrays
// single dimensional array
//names[1] = "Zubia";
94
//names[2] = "Saad";
21
59
//[Link](names[0]);
//[Link](names[1]);
07
//[Link](names[2]);
80
// 4 types of loops
// for loop
.in
ys
// while loop
// do while loop
ra
//nums[0] = 11;
//nums[1] = 22;
//nums[2] = 33;
//nums[3] = 44;
//[Link](nums[2]);
[Link]();
94
}
21
}
59
07
80
.in
ys
ra
ar
ith
w
de
co
CLASSES AND OBJECTS IN C#
C# programs are composed of classes that represent the entities
of the program which also include code to instantiate the classes
as objects.
When the program runs, objects are created for the classes and
they may interact with each other to provide the functionalities of
the program.
An object is a tangible entity such as a car, a table, or a briefcase.
Every object has some characteristics and is capable of
94
performing certain actions.
The concept of objects in the real world can also be extended to
21
the programming world. An object in a programming language has
59
a unique identity, state, and behavior.
The state of the object refers to its characteristics or attributes
07
whereas the behavior of the object comprises its actions.
80
An object has various features that can describe it which could be
the company name, model, price, mileage, and so on.
.in
ys
ra
ar
ith
w
de
co
The concept of classes in the real world can be extended to the
programming world, similar to the concept of objects.
In object-oriented programming languages like C#, a class is a
template or blueprint which defines the state and behavior of all
objects belonging to that class.
A class comprises fields, properties, methods, and so on,
collectively called data members of the class. In C#, the class
declaration starts with the class keyword followed by the name of
the class.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
ABSTRACT CLASS AND ABSTRACT METHODS IN C#
A class which contains the abstract keyword in its declaration is known as
abstract class.
Abstract classes may or may not contain abstract methods, i.e., methods
without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared
abstract.
94
To use an abstract class, you have to inherit it from another class, provide
21
implementations to the abstract methods in it.
59
If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
07
Like any other class, an abstract class can contain fields that describe the
characteristics and methods that describe the actions that a class can perform.
80
ABSTRACT METHODS
.in
An abstract method contains a method signature, but no method
body.
ys
You have to place the abstract keyword before the method name
in the method declaration.
w
94
reusability of code and to reduce complexity in code and it is
21
possible by using inheritance.
59
07
EMPLOYEE
80
Int EmpId;
String EmpName; Parent Class
Int EmpAge;
.in
Int EmpContactNo;
ys
Child Class Child Class
ra
The inheritance concept is based on a base class and derived class. Let
us see the definition of a base and derived class.
BASE CLASS - is the class from which features are to be inherited
into another class.
DERIVED CLASS - it is the class in which the base class features are
inherited.
Single Inheritance
94
It is the type of inheritance in which there is one base class and one
derived class.
21
59
07
80
.in
ys
ra
ar
ith
w
Definition of Inheritance
de
94
21
59
07
80
.in
ys
ra
ar
ith
w
Example
de
co
07
The similarity in physical features of a child to that of its
80
parents is due to the child having inherited these features
from its parents.
Similarly, in C#, inheritance allows you to create a class by
.in
deriving the common attributes and methods of an existing
ys
class.
Inheritance provides reusability by allowing us to extend an
ra
existing class.
ar
80
The purpose of inheritance is to reuse common methods and
attributes among classes without recreating them.
.in
Reusability of a code enables you to use the same code in
ys
different applications with little or no changes.
ra
Example
ar
ith
previously-defined class.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
1. Generalization
2. Specialization
3. Extension
Generalization
Inheritance allows you to implement generalization by
creating base classes. For example, consider the class
Vehicle, which is the base class for its derived classes Truck
and Bike.
The class Vehicle consists of general attributes and methods
that are implemented more specifically in the respective
derived classes.
Specialization
Inheritance allows you to implement specialization by
creating derived classes.
For example, the derived classes such as Bike, Bicycle, Bus,
94
and Truck are specialized by implementing only specific
methods from its generalized base class Vehicle.
21
Extension
59
Inheritance allows you to extend the functionalities of a
07
80
are not present in the base class. It allows you to provide
additional features to the existing derived class without
modifying the existing code. .in
ys
The following figure displays a real-world example
demonstrating the purpose of inheritance:
ra
ar
ith
w
de
co
94
21
59
07
80
.in
ys
ra
94
If u don’t write base() explicitly then C# compiler implicitly write
21
the base().
If base Class have parameterized constructor then you can add
59
parameters in base().
07
Base Keyword
80
The base keyword allows you to do the following:
.in
Access the variables and methods of the base class from the
ys
derived class.
Re-declare the methods and variables defined in the base
ra
class.
ar
class <ClassName>
{
co
<accessmodifier><returntype><BaseMethod>{}
}
class <ClassName1>:<ClassName>
{
base.<BaseMethod>;
}
where,
<ClassName>: Is the name of the base class.
<accessmodifier>: Specifies the scope of the class or
method.> : Specifies the scope of the class or method.
<returntype>: Specifies the type of data the method will
return.
<BaseMethod>: Is the base class method.
<ClassName1>: Is the name of the derived class.
base: Is a keyword used to access the base class members.
The following figure displays an example of using the base
keyword:
94
21
59
07
80
.in
ys
ra
ar
Constructor In Inheritance
ith
94
21
59
07
80
.in
The following code explicitly invokes the base class
constructor using the base keyword:
ys
class Animal
ra
{
public Animal()
ar
{
[Link]("Animal constructor without parameters");
ith
}
public Animal(Stringname)
{
w
}
}
class Canine:Animal
co
{
//base()takes a string value called“Lion”
public Canine():base("Lion")
{
[Link]("DerivedCanine");
}
}
class Details
{
static voidMain(String[]args)
{
Canine objCanine=new Canine();
}
}
In Above code,
The class Animal consists of two constructors, one without a
parameter and the other with a string parameter.
The class Canine is inherited from the class Animal.
The derived class Canine consists of a constructor that
invokes the constructor of the base class Animal by using the
base keyword.
If the base keyword does not take a string in the parenthesis,
94
21
parameters is invoked.
In the class Details, when the derived class constructor is
59
07
of the base class.
80
Output
Animal constructor with a string parameter .in
Derived Canine
ys
constructor declaration.
If there are no parameters, the base keyword is followed by a
co
pair of parentheses.
The following code demonstrates how parameterized
constructors are invoked in a multi-level hierarchy:
using System;
class Metals
{
string_metalType;
public Metals(stringtype)
{
_metalType=type;
[Link]("Metal:\t\t"+_metalType);
}
}
class SteelCompany : Metals
{
string_grade;
public SteelCompany(stringgrade):base("Steel")
{
_grade=grade;
[Link]("Grade:\t\t"+_grade);
}
}
class Automobiles:SteelCompany
{
94
string_part;
public Automobiles(stringpart):base("CastIron")
{
21
_part=part;
[Link]("Part:\t\t"+_part);
59
}
static voidMain(string[]args)
{
07
Automobiles objAutomobiles=new Automobiles("Chassies");
}
}
80
In Above code,
.in
The Automobiles class inherits the SteelCompany class.
The SteelCompany class inherits the Metals class.
ys
class.
Finally, the constructor of the Automobiles class is invoked.
w
de
Output
co
Metal: Steel
Grade: CastIron
Part: Chassies
Source Code Of Constructor In Inheritance
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace Constructor_In_Inheritance
{
class BaseClass
{
public BaseClass(string message)
{
[Link](message);
}
public BaseClass(int i)
{
[Link](i);
}
94
}
21
class DerivedClass : BaseClass
{
public DerivedClass() : base(25)
59
{
[Link]("this is a constructor of Derived class !!");
07
}
80
}
class Program
{
static void Main(string[] args) .in
{
DerivedClass dc = new DerivedClass();
ys
[Link]();
}
}
ra
}
ar
ith
w
de
co
types of inheritance in C#
The following are the types of inheritance in C#
94
21
There are 4 types of Inheritance in C#
59
1. Single
07
2. Multi-level
80
3. Hierarchical
4. Multiple
.in
The inheritance concept is based on a base class and derived class.
Let us see the definition of a base and derived class.
ys
ra
Single Inheritance In C#
de
co
21
Source Code Of Single Inheritance
59
using System;
07
using [Link];
using [Link];
using [Link];
80
using [Link];
namespace INHERITANCE_CSHARP
{
class Employees
{
ith
class Program
{
static void Main(string[] args)
{
PermanentEmployees Asad = new PermanentEmployees();
[Link] = 12;
[Link]();
[Link]([Link]);
[Link]();
}
}
}
Hierarchical Inheritance
94
This is the type of inheritance in which there are multiple
21
59
This type of inheritance is used when there is a requirement
of one class feature that is needed in multiple classes.
07
80
.in
ys
ra
Multilevel Inheritance
ar
ith
When one class is derived from another derived class then this
type of inheritance is called multilevel inheritance.
w
de
co
94
21
59
Multi-level Inheritance
07
Inheritance allows the programmer to build hierarchies that can
contain multiple levels of inheritance.
80
Example .in
Consider three classes Mammal, Animal, and Dog. The class
ys
Mammal is inherited from the base class Animal, which
ra
classes.
w
classes:
co
The following code demonstrates multiple levels of
inheritance:
using System;
class Animal
{
public void Eat()
{
[Link](“Every animal eats something.”);
}
}
94
class Mammal : Animal
{
public void Feature()
21
{
[Link](“Mammals give birth to young ones.”);
59
}
}
07
class Dog : Mammal
{
public void Noise()
80
{
[Link](“Dog Barks.”);
}
static void Main(string[] args)
{
Dog objDog = new Dog();
.in
[Link]();
ys
[Link]();
[Link]();
ra
}
}
ar
ith
In Above code, the Main() method of the class Dog invokes the
methods of the class Animal, Mammal, and Dog.
w
de
Output
co
94
21
59
07
FATHER SON HUSBAND TEACHER
80
There Are Two Types Of Polymorphism
.in
1. Static Polymorphism (Compile Time Polymorphism)
ys
2. Dynamic Polymorphism (Run Time Polymorphism)
ra
ar
ith
w
de
co
Static Polymorphism (Compile Time Polymorphism) In C#
The mechanism of linking a function with an object during
compile time is called static polymorphism or early binding.
It is also called static binding.
C# provides two techniques to implement static polymorphism. They
are −
Method Or Function Overloading
94
Operator Overloading
21
59
Method Or Function Overloading
07
You can have multiple definitions for the same function
80
name in the same scope.
The definition of the function must differ from each other
.in
by the types and/or the number of arguments in the
ys
argument list.
You cannot overload function declarations that differ only
ra
by return type.
ar
ith
w
de
co
Dynamic Or Runtime Polymorphism In C#
Run time polymorphism is achieved by method overriding.
Method overriding allows us to have virtual and abstract methods
in the base using derived classes with the same name and the
same parameter.
C# Method Overriding
If derived class defines same method as defined in its base
94
class, it is known as method overriding in C#.
21
It is used to achieve runtime polymorphism.
59
It enables you to provide specific implementation of the
method in child class which is already provided by its base
07
class.
80
To perform method overriding in C#, you need to use
virtual keyword with base class method and override
.in
keyword with derived class method.
ys
A method declared using the virtual keyword is referred to
as a virtual method.
ra
derived class.
The override keyword overrides the base class method in
the derived class.
Difference Between Method Hiding And Method Overriding In C#
94
21
59
07
80
METHOD HIDING OUTPUT .in METHOD OVERRIDING OUTPUT
ys
ra
ar
In method hiding, a base class reference variable In method overriding, a base class reference
pointing to a child class object, will invoke the variable pointing to a child class object, will invoke
ith
hidden method of the base class. the overridden method of the child class.
w
de
co
Constructor Overloading
Declaring more than one constructor in a class is called
constructor overloading.
The process of overloading constructors is similar to
overloading methods where every constructor has a signature
similar to that of a method.
Multiple constructors in a class can be declared wherein each
94
21
Constructor overloading is used when different objects of the
class might want to use different initialized values.
59
Overloaded constructors reduce the task of assigning
07
different values to member variables each time when needed
by different objects of the class.
80
The following code demonstrates the use of constructor
overloading: .in
ys
using System;
public class Rectangle
{
ra
double _length;
double _breadth;
ar
public Rectangle()
{
ith
}
_length = 13.5;
_breadth = 20.5;
w
}
de
_breadth = wide;
}
In Above Code,
Two constructors are created having the same name,
Rectangle.
However, the signatures of these constructors are different.
94
Hence, while calling the method Area()from the Main()
method, the parameters passed to the calling method are
21
identified.
59
Then, the corresponding constructor is used to initialize the
variables _length and _breadth. Finally, the multiplication
07
operation is performed on these variables and the area values
are displayed as the output.
80
Output .in
Area of rectangle1 = 276.75
ys
Area of rectangle2 = 17.25
ra
using System;
using [Link];
using [Link];
w
using [Link];
using [Link];
de
namespace ConstructorOverloading
{
co
class Program
{
public Program()
{
[Link]("this is a first constructor !!");
}
public Program(int a, int b)
{
[Link]("this is a Second constructor !! {0}", (a+b));
}
public Program(int a, int b, int c)
{
[Link]("this is a third constructor !! {0}", (a + b
+c));
}
public Program(string a, string b, string c)
{
[Link]("this is a fourth constructor !! {0}", (a + b +
c));
}
94
{
// CONSTRUCTOR OVERLOADING
21
Program p = new Program("A","B","C");
[Link]();
}
59
}
}
07
80
.in
ys
ra
ar
ith
w
de
co
ABSTRACT CLASS IN C#
The word abstract means a concept or an idea not associated with any specific
instance. In programming we apply the same meaning of abstraction by making
classes not associated with any specific instance.
The abstraction is done when we need to only inherit from a certain class, but not
need to instantiate objects of that class.
In C#, abstraction is achieved using Abstract classes and interfaces.
Abstract Class:
94
C# Abstract classes are used to declare common characteristics of
subclasses.
21
A class which contains the abstract keyword in its declaration is
59
known as abstract class.
It can only be used as a BASE class for other classes that extend
07
the abstract class.
80
Abstract classes may or may not contain abstract methods, i.e.,
methods without body ( public void get(); )
Like any other class, an abstract class can contain fields that
.in
describe the characteristics and methods that describe the actions
ys
that a class can perform.
ra
But, if a class has at least one abstract method, then the class
ar
ra
ys
.in
80
07
TEACHER
59
21
94
ABSTRACT PROPERTIES IN C#
The word Abstract means incomplete, which means no implementation in
programming.
This is a duty of child class to implement an abstract member of their
parent class.
Declared by using the abstract keyword.
Contain only the declaration of the property without the body of the get
and set accessors (which do not contain any statements and can be
implemented in the derived class).
Are only allowed in an abstract class.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
INTERFACES IN C#
An interface is a contract between itself and any class that implements it.
This contract states that any class that implements the interface will
implement the interface's properties, methods and/or events. An interface
contains no implementation, only the signatures of the functionality the
interface provides. An interface can contain signatures of methods,
properties, indexers & events.
The interface defines the 'what' part of the syntactical contract and the
deriving classes define the 'how' part of the syntactical contract.
94
Interfaces define properties, methods, and events, which are the members
of the interface. Interfaces contain only the declaration of the members. It
21
is the responsibility of the deriving class to define the members.
59
One of the main reason to introduce interfaces is that it can be used in
multiple inheritance.
07
An interface contains only abstract members, just like classes interface also
80
contains properties, methods, delegates or events, but only declarations,
no implementations.
An interface cannot be instantiated but can only be inherited by classes or
other interfaces.
.in
Interface cannot have fields.
ys
An interface is declared using the keyword interface.
ra
IMPLEMENTING AN INTERFACE
An interface is implemented by a class in a way similar to inheriting a class.
w
methods declared in the interface. If all the methods are not implemented,
co
INTERFACE INHERITANCE IN C#
Interface can inherit from other interfaces.
A class that inherits this interface must provide implementation
for all interface members in the entire interface inheritance chain.
Interface reference variable can have the reference of their child
class.
Sealed Methods In C#
When the derived class overrides a base class method, variable,
property or event, then the new method, variable, property, or
event can be declared as sealed.
Sealing the new method prevents the method from further
overriding.
An overridden method can be sealed by preceding the override
keyword with the sealed keyword.
94
Steps To Remember For Sealed Methods:
21
Sealed method is always an override method of child class.
We cannot again override the sealed method.
59
Sealed method is only available with Method Overriding.
07
Sealed keyword is not available with the method hiding.
80
Sealed is used together with override method.
We cannot make normal methods as sealed.
.in
ys
ra
ar
ith
w
de
co
SEALED CLASS IN C# PROGRAMMING
A sealed class is a class that prevents inheritance.
The features of a sealed class are as follows:
A sealed class can be declared by preceding the class keyword
with the sealed keyword.
The sealed keyword prevents a class from being inherited by any
other class.
The sealed class cannot be a base class as it cannot be inherited
94
by any other class. If a class tries to derive a sealed class, the C#
compiler generates an error.
21
Purpose of Sealed Classes
59
Consider a class named SystemInformation that consists of
07
critical methods that affect the working of the operating system.
80
You might not want any third party to inherit the class
SystemInformation and override its methods, thus, causing
security and copyright issues.
.in
ys
Here, you can declare the SystemInformation class as sealed to
ra
94
The features of a sealed class are as follows:
21
A sealed class can be declared by preceding the class
keyword with the sealed keyword.
59
The sealed keyword prevents a class from being inherited
07
by any other class.
The sealed class cannot be a base class as it cannot be
80
You might not want any third party to inherit the class
de
where,
sealed: Is a keyword used to prevent a class from being
inherited.
ClassName: Is the name of the class that needs to be
sealed.
94
The following code demonstrates the use of a sealed class in
21
C# which will generate a compiler error:
59
sealed class Product
{
07
public int Quantity;
public int Cost;
}
80
class Goods
{
static void Main(string [] args)
{
Product objProduct = new Product();
[Link] = 50;
.in
[Link] = 75;
ys
[Link](“Quantity of the Product: “ + objProduct. Quantity);
[Link](“Cost of the Product: “ + [Link]);
ra
}
}
class Pen : Product
ar
{
}
ith
In Above Code,
w
de
94
21
Guidelines
59
Sealed classes are restricted classes that cannot be inherited
07
where the list depicts the conditions in which a class can be
marked as sealed:
80
o If overriding the methods of a class might result in
using System;
using [Link];
ith
using [Link];
using [Link];
w
using [Link];
de
namespace SEALED_CLASS
{
sealed class ParentClass
co
{
public void Show1()
{
[Link]("This is the method of parent class !!");
}
}
class Program
{
static void Main(string[] args)
{
ChildClass obj = new ChildClass();
}
}
}
94
Sealed Methods In C#
21
[Link]
59
v=m816QtdzDJI&list=PLX07l0qxoHFLZftsVKyj3k9kfMca2uaPR&index=66
07
When the derived class overrides a base class method,
variable, property or event, then the new method, variable,
80
property, or event can be declared as sealed.
Sealing the new method prevents the method from further
.in
overriding.
An overridden method can be sealed by preceding the
ys
94
sealed:
21
using System;
class ITSystem
59
{
public virtual void Print()
{
07
[Link] (“The system should be handled carefully”);
}
80
}
class CompanySystem : ITSystem
{
public override sealed void Print()
{ .in
[Link] (“The system information is
confidential”);
ys
[Link] (“This information should not be
overridden”);
}
ra
}
class SealedSystem : CompanySystem
ar
{
public override void Print()
ith
{
[Link] (“This statement won’t get
executed”);
w
}
de
[Link] ();
}
}
In Above Code,
The class ITSystem consists of a virtual function Print().
The class CompanySystem is inherited from the class
ITSystem.
It overrides the base class method Print().
The overridden method Print() is sealed by using the sealed
keyword, which prevents further overriding of that method.
The class SealedSystem is inherited from the class
CompanySystem.
94
When the class SealedSystem overrides the sealed method
Print(), the C# compiler generates an error as shown in the
21
following figure:
59
07
80
.in
ys
ra
ar
ith
using System;
using [Link];
using [Link];
co
using [Link];
using [Link];
namespace SEALED_METHOD
{
class A
{
public void Print()
{
[Link]("This is a method of Class A !!");
}
}
class B : A
{
public new void Print()
{
[Link]("This is a method of Class B !!");
}
}
//class C : B
//{
// public override void Print()
// {
// [Link]("This is a method of Class C !!");
94
// }
//}
21
class Program
{
59
static void Main(string[] args)
{
A obj = new B();
07
[Link]();
80
//[Link]();
[Link]();
}
} .in
ys
ra
ar
ith
w
de
co
Delegates In C# Programming
Delegate meaning from google: a person sent or authorized to represent
others, in particular an elected representative sent to a conference.
Delegate is a type which holds a method’s reference in an object.
It is also called function pointer.
Delegate is of reference type.
Delegate signature should be as same as the method signature referencing
by a delegate.
Delegate can point to a parameterized method or non-paramterized
method.
94
Delagate has no implementation means no body with { }.
We can use invoke() method with delegates.
21
Delegates are used to encapsulate methods.
59
In the .net framework, a delegate points to one or more methods. Once
you instantiate the delegate, the corresponding methods invoke.
07
Delegates are objects that contain references to methods that need to be
invoked instead of containing the actual method names
80
Using delegates, you can call any method, which is identified only at run-
time.
.in
A delegate is like having a general method name that points to various
methods at different times and invokes the required method at run-time.
ys
In c#, invoking a delegate will execute the referenced method at run-time.
ra
94
NOTE: If we do not use “new” keyword then compiler will raise only warning, but,
21
program will work fine.
59
Different Ways To Call A Hidden Base Class Member From Derived Class
07
1. Use base keyword
2. Cast child type to parent type and invoke the hidden member.
80
3. ParentClass PC = new ChildClass();
[Link]();
.in
Parent class can have the reference of its child class.
ys
When we create the object of child class, parent class object is also created.
ra
ar
ith
w
de
co
Indexer In C# Programming
Indexers allow our object to be used just like an array, or we can say we can index
the object using [ ] brackets just like arrays.
We can say indexers are special type of properties which adds logic that how can
array or list store the values.
Syntax of indexer resembles to properties.
We can use all access modifiers with indexers and also have return types.
Indexers are the regular members of a class.
94
Indexer is created with the help of this keyword.
In C# introduce new concept is Indexer. This is very useful for some situation. Let
21
as discuss something about Indexer.
59
Indexer Concept is object act as an array.
Indexer an object to be indexed in the same way as an array.
07
Indexer modifier can be private, public, protected or internal.
80
The return type can be any valid C# types.
Indexers in C# must have at least one parameter. Else the compiler will
generate a compilation error. .in
ys
ra
ar
ith
w
de
co
Collections In C# Programming
ARRAY COLLECTION
Cannot be resized at run-time. Can be resized at run-time.
The individual elements are of the The individual elements can be of
same data type. different data types.
94
We can never insert a value into a We can insert a value into a middle of a
21
middle of an array. collection.
59
We can never delete a value from We can delete a value from a middle of
a middle of an array. a collection.
07
A Collection is a set of related data that may not necessarily belong to the
80
same data type that can be set or modified dynamically at run-time.
In other words, collection is a dynamic array.
.in
o Its Length can increase on runtime. AUTO RESIZING
Normal Array’s length is fixed, it means we cannot change the length after
ys
declaring an array.
ra
[Link]()
Resize method of an array destroys old array and create a new array with
ar
new length.
ith
do this then array length should be increased but we cannot increase the
length of an array after declaring the length of an array.
de
94
21
59
07
80
.in
ys
ra
Capacity property which tells number of items that can be stored under any collection.
INSERT METHOD.
ith
94
Consider a code that calculates the area of the circle.
To calculate the area of the circle, the value of pi and radius
21
59
The value of pi is a constant value.
This value will remain unchanged irrespective of the value
07
80
Similarly, constants in C# are fixed values assigned to
identifiers that are not modified throughout the execution of
the code. .in
They are defined when you want to preserve values to reuse
ys
them later or to prevent any modification to the values.
ra
Constants In C#
ar
ith
declaration.
Constants are declared for value types rather than for
reference types.
To declare an identifier as a constant, the “const” keyword
is used in the identifier declaration. The compiler can
identify constants at the time of compilation, because of the
“const” keyword.
The following syntax is used to initialize a constant:
const<data type><identifier name> = <value>;
where,
94
const: Keyword denoting that the identifier is declared as
21
constant.
data type: Data type of constant.
59
identifier name: Name of the identifier that will hold the
07
constant.
value: Fixed value that remains unchanged throughout the
80
execution of the code.
The following code declares a constant named _pi and a
.in
variable named radius to calculate the area of the circle:
ys
const float _pi = 3.14F;
ra
float radius = 5;
float area = _pi * radius * radius;
ar
In Above Code,
w
Literals In C# Programming
A literal is a static value assigned to variables and
constants.
Numeric literals might suffix with a letter of the alphabet to
indicate the data type of the literal.
This letter can be either in upper or lowercase.
Example
For example, in the following declaration,
94
string bookName = “Csharp”
21
Csharp is a literal assigned to the variable bookName of type
string.
59
Types Of Literals
07
Boolean Literal
80
Integer Literal
Real Literal .in
Character Literal
ys
String Literal
Null Literal
ra
ar
Boolean Literal
ith
where,
co
Integer Literal
Integer Literal: An integer literal can be assigned to int,
uint, long, or ulongdata types. Suffixes for integer literals
include U, L, UL, or LU. U denotes uint or ulong, L
denotes long. UL and LU denote ulong. For example,
o long val = 53L;
Where,
o 53L: Is an integer literal assigned to the variable val.
Real Literal
94
Real Literal: A real literal is assigned to float, double
21
(default), and decimal data types. This is indicated by the
suffix letter appearing after the assigned value. A real
59
literal can be suffixed by F, D, or M. F denotes float, D
07
denotes double, and M denotes decimal. For example,
o float val = 1.66F;
80
Where,
o 1.66F: Is a real literal assigned to the variable val.
.in
Character Literal
ys
Where,
de
String Literal
String Literal: There are two types of string literals in C#,
regular and verbatim. A regular string literal is a standard
string. A verbatim string literal is similar to a regular string
literal but is prefixed by the ‘@’ character. A string literal
is always enclosed in double quotes. For example,
ostring mailDomain = “@[Link]”;
Where,
o @[Link]: Is a verbatim string literal.
Null Literal
Null Literal: The null literal has only one value, null. For
example,
94
o string email = null;
21
Where,
o null: Specifies that e-mail does not refer to any objects
59
(reference).
07
80
.in
ys
ra
ar
ith
w
de
co
GENERICS IN C# PROGRAMMING
Generics introduced in C# 2.0.
Generics allow you to write a class or method that can work with
any data type.
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. It helps you
to maximize code reuse, type safety, and performance.
You can create your own generic interfaces, classes, methods,
94
events, and delegates.
21
You may get information on the types used in a generic data type
at run-time.
59
A generic class or method can be defined using angle brackets <>
07
Generics can be applied to the following:
80
Interface
Abstract class .in
Class
ys
Method
Static method
ra
Property
ar
Event
ith
Delegates
w
Operator
de
Advantages of Generic:
co
94
declarations.
21
Generic methods can be declared with the following keywords:
59
Virtual
Override
07
Abstract
80
.in
ys
ra
ar
ith
w
de
co
GENERIC CLASS IN C# PROGRAMMING
Generic classes define functionalities that can be used for any
data type and are declared with a class declaration followed by a
type parameter enclosed within angular brackets.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co
[Link]
94
[Link]
21
59
07
[Link] Group Link: [Link]
80
.in
+91 8007592194 +91 9284926333
ys
ra
ar
ith
codewitharrays@[Link]
w
de
co
[Link]