0% found this document useful (0 votes)
47 views187 pages

C Sharp Notes by Ashok

Uploaded by

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

C Sharp Notes by Ashok

Uploaded by

bhumi031811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

freelance_Project available to buy contact on 8007592194

[Link] NAME Technology


1 Online E-Learning Platform Hub React+Springboot+MySql

94
2 PG Mates / RoomSharing / Flat Mates React+Springboot+MySql

21
3 Tour and Travel management System React+Springboot+MySql

4 Election commition of India (online Voting System) React+Springboot+MySql

59
5 HomeRental Booking System React+Springboot+MySql

07
6 Event Management System React+Springboot+MySql

7 Hotel 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

Introduction To C# (C-Sharp) Programming


 Microsoft introduced a new language called C# (pronounced C Sharp). C# is designed to
be a simple, modern, general-purpose, object-oriented programming language, borrowing
key concepts from several other languages, most notably Java.
 C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.
 C# is a part of .NET Framework.
 Microsoft introduced C# as a new programming language to address

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

What is .Net Framework ?


de

.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.

Microsoft C# Was Developed To

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

 Provide a consistent developer experience across varying types of applications such as


Windows-based applications and Web-based applications.
ar

 It has language-specific features, such as:


ith

o Type safety checking


w

o Generics
o Indexers
de

 These features make the C# as a preferred language to create a wide variety of


co

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

 It is a completely new platform for developing the next generation of


Windows/Web applications.
 These applications transcend device boundaries and fully harness the
power of the Internet.
 However, building the new platform required a language that could
take full advantage.
 This is one of the factors that led to the development of C#.

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

object-oriented language that is familiar and yet at the same time

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

o Standardization by European Computer Manufacturers


ith

Association (ECMA)
o Generic Types and Methods
w

o Iterators
de

o Methods with named Arguments


co

o Methods with optional Arguments

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

(ECMA): Specifies the syntax and constraints used to create standard

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

source code (.cs) files.


Anonymous Methods: Enable the user to specify a small block of
w

code within the delegate declaration.


de

 Methods with named Arguments: Enable the user to associate a


co

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

 Auto-implemented Properties: Allow the user to create a property


without explicitly providing the methods to get and set the value of
the property.
 Parallel Computing: Support for parallel programming using which
develop efficient, fine-grained, and scalable parallel code without
working directly with threads or the thread pool.

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

 Large-scale enterprise applications


Complex distributed applications that can spread over a number of
ar

cities or countries
ith
w

The CLR
de

 Is the foundation of the .NET Framework.


 Acts as an execution engine for the .NET Framework.
co

 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

By Using DotNet Framework


 A programmer can develop applications using one of the languages
supported by .NET.
 These applications make use of the base class libraries provided by
the .NET Framework.
 The .NET Framework supports a number of development tools and

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

DotNet Framework Class Library (FCL)


ra
ar

 Is a comprehensive object-oriented collection of reusable types.


ith

 Is used to develop applications ranging from traditional command-


line to Graphical User Interface (GUI) applications that can be used
w

on the Web.
de

DotNet Framework Components


co

 Common Language Specification (CLS)


 Common Type System (CTS)
 Base Framework Classes
 WPF
 [Link]
 WCF
pg. 6
DOTNET NOTES BY ASHOK PATE

 [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

Provides classes to interact with databases.


ar


ith

[Link]
w

 Provides a set of classes to build Web applications. [Link] Web


de

applications can be built using Web Forms, which is a set of classes


to design forms for the Web pages similar to the HTML.
co

 Supports Web services that can be accessed using a standard set of


protocols.
WCF
 Is a service-oriented messaging framework.
 Allows creating service endpoints and allows programs to
asynchronously send and receive data from the service endpoint.
pg. 7
DOTNET NOTES BY ASHOK PATE

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

Task Parallel Library


ra
ar

 Is a library that simplifies parallel and concurrent programming in


a .NET application.
ith
w

When a code is executed for the first time


de

 The CIL (COMMON INTERMEDIATE LANGUAGE) code is converted to a


co

code native to the operating system.


 This is done at runtime by the Just-In-Time (JIT) compiler present in the CLR.
 The CLR converts the CIL code to the machine language code.
 Once this is done, the code can be directly executed by the CPU.

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

The CLR provides many features such as:


 Memory management
 Code execution
 Error handling
pg. 9
DOTNET NOTES BY ASHOK PATE

 Code safety verification


 Garbage collection
The applications that run under the CLR are called managed code.
The CLR manages code at execution time and performs operations such
as:

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

CIL - Common Intermediate Language


 Every .NET programming language generally has a compiler and a
runtime environment of its own.
pg. 10
DOTNET NOTES BY ASHOK PATE

 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

What Is Memory Management ?


de

In programming languages like C and C++, the allocation and de-


co

allocation of memory is done manually.


 Performing these tasks manually is both, time-consuming and
difficult.
 The C# language provides the feature of allocating and releasing
memory using automatic memory management.

pg. 11
DOTNET NOTES BY ASHOK PATE

 This means that there is no need to write code to allocate memory


when objects are created or to release memory when objects are not
required in the application.
 Automatic memory management increases the code quality and
enhances the performance and the productivity.
What Is Garbage Collection ?

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

memory using automatic memory management.

07
Below figure describes concept of garbage collection:

80
.in
ys
ra
ar
ith
w
de
co

pg. 12
DOTNET NOTES BY ASHOK PATE

DLR - Dynamic Language Runtime


 Is a runtime environment built on top of the CLR to enable
interoperability of dynamic languages such as Ruby and Python with
the .NET Framework.
 Allows creating and porting dynamic languages to the .NET
Framework.

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

environment for programs to run.


ar

o Provides a multi-language execution environment.


ith

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

 A namespace is used in C# to group classes logically and prevent


de

name clashes between classes with identical names.


A namespace reduces any complexities when the same program is
co

required in another application.


 A namespace is used to organize your code and is collection of
classes, interfaces, structs, enums and delegates.
 NOTE: if u don’t want to use namespace you can use Fully
Qualified Name (FQN).

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

with their respective countries.


ar

 Similarly, when working on a huge project, there may be situations


ith

where classes have identical names.


This may result in name conflicts.
w

This problem can be solved by having the individual modules of the


de

project use separate namespaces to store their respective classes.


co

 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

 Each of the identical classes is placed in their respective namespaces,


which denote respective company names.
 It can be observed that this is a neater, better organized, and more
structured way to handle naming conflicts.
Using Namespaces In C#
C# allows you to specify a unique identifier for each namespace.

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

events, indexers, methods, and properties.


 Interfaces are inherited by classes and structures and all the
.in
declarations are implemented in these classes and structures.
ys

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

indexers, operators, and other structures.


w
de

Enumeration
co

 An enumeration is a value type that consists of a list of named


constants.
 This list of named constants is known as the enumerator list.
Delegate
 A delegate is a user-defined reference type that refers to one or more
methods.
pg. 17
DOTNET NOTES BY ASHOK PATE

 It can be used to pass data as parameters to methods.


Advantages & Characteristics Of Namespaces
 A namespace groups common and related classes, structures, or
interfaces, which support OOP concepts of encapsulation and
abstraction.
A namespace provides a hierarchical structure that helps to identify

94

the logic for grouping the classes.

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

The .NET Framework comprises several built-in namespaces that


ar

contain:
ith

o Classes
w

o Interfaces
de

o Structures

o Delegates
co

o Enumerations

 These namespaces are referred to as system-defined namespaces.


 The most commonly used built-in namespace of the .NET
Framework is System.
 The System namespace contains classes that:
o Define value and reference data types, interfaces, and other

namespaces.
pg. 18
DOTNET NOTES BY ASHOK PATE

o Allow you to interact with the system, including the standard


input and output devices.
Pre-defined Namespaces
Some of the most widely used namespaces within the System
namespace are as follows:

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

 The [Link] namespace contains classes that are used to


interact with the system processes.
w

This namespace also provides classes that are used to debug


de

applications and trace the execution of the code.


co

[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

 The [Link] namespace contains classes that allow you to create


Web-based applications.
[Link]
 The [Link] namespace provides classes and interfaces that
allow communication between the browser and the server.

94
The following figure displays some built-in namespaces:

21
59
07
80
.in
ys
ra
ar
ith
w
de

System Namespace in .Net Framework


co

 The System namespace is imported by default in the .NET


Framework.
 It appears as the first line of the program along with the using
keyword.
 For referring to classes within a built-in namespace, you need to
explicitly refer to the required classes.

pg. 20
DOTNET NOTES BY ASHOK PATE

 It is done by specifying the namespace and the class name separated


by the dot (.) operator after the using keyword at the beginning of the
program.
 You can refer to classes within the namespaces in the same manner
without the using keyword.
 However, this results in redundancy because you need to mention the
whole declaration every time you refer to the class in the code.

94
The two approaches of referencing the System namespace are:

21
59
07
80
.in
ys
ra
ar
ith
w

Though both are technically valid, the first approach is more


de

recommended.
co

The following syntax is used to access a method in a


system-defined namespace:
<NamespaceName>.<ClassName>.<MethodName>;

In Above Syntax,
 NamespaceName: Is the name of the namespace.
pg. 21
DOTNET NOTES BY ASHOK PATE

 ClassName: Is the name of the class that you want to access.


 MethodName: Is the name of the method within the class that is to be
invoked.
The following syntax is used to access the system-defined namespaces
with the using keyword:
using <NamespaceName>;

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

The following code refers to the Console class of the System


namespace multiple times:
class World
{
static void Main(string[] args)
{
[Link](“Hello World”);
[Link](“This is C# Programming”);
[Link](“You have executed a simple program of
C#”);

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

 C# allows you to create namespaces with appropriate names to


ar

organize structures, classes, interfaces, delegates, and enumerations


ith

that can be used across different C# applications.


When using a custom namespace, you need not worry about name
w

clashes with classes, interfaces, and so on in other namespaces.


de

 Custom namespaces:
co

o Enable you to control the scope of a class by deciding the

appropriate namespace for the class.


o Declared using the namespace keyword and is accessed with the

using keyword similar to any built-in namespace.


The following syntax is used to declare a custom namespace:
namespace <NamespaceName>
{

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

 The class Sales is declared within this namespace.


ar

Output
ith

You have created a custom namespace named Department


w
de

 Once a namespace is created, C# allows:


co

o Additional classes to be included later in that namespace. Hence,

namespaces are additive.


o A namespace to be declared more than once.

 These namespaces can be split and saved in separate files or in the


same file.
 At the time of compilation, these namespaces are added together.
Important Guidelines for Creating Custom Namespaces
pg. 24
DOTNET NOTES BY ASHOK PATE

 While designing a large framework for a project, it is required to


create namespaces to group the types into the appropriate namespaces
such that the identical types do not collide.
 Therefore, the following guidelines must be considered for creating
custom namespaces:
o All similar elements such as classes and interfaces must be

created into a single namespace. This will form a logical

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

Reading & Writing To The Console In C# Application


ra
ar

Input & Output In C# Program


ith

 Programmers often need to display the output of a C# program to


w

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

 Console operations are tasks performed on the command line


interface using executable commands.
 The console operations are used in software applications because
these operations are easily controlled by the operating system.
 This is because console operations are dependent on the input and
output devices of the computer system.
 A console application is one that performs operations at the command

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

application for processing.


w

Standard out
de
co

The standard out stream displays the output on the monitor.


Standard err
The standard err stream displays error messages on the monitor.
Output Methods In C#

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.

o [Link](): Writes any type of data and this data ends

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

 variables: Specify variable names whose value should be displayed


ith

on the console.
w

The following syntax is used for the [Link]() method,


de

which allows you to display the information on a new line in the


console window:
co

[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

int number, result;


number = 5;
result = 100 * number;
ar

[Link](“Result is {0} when 100 is multiplied by {1}”, result,number);


result = 150 / number;
ith

[Link](“Result is {0} when 150 is divided by {1}”, +result, number);


w

Output
de

Result is 500 when 100 is multiplied by 5


co

Result is 30 when 150 is divided by 5


Here, {0} is replaced with the value in result and {1} is replaced with the
value in number.
Input Methods In C#
 In C#, to read data, you need the standard input stream. This stream is
provided by the input methods of the Console class. There are two
pg. 28
DOTNET NOTES BY ASHOK PATE

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.

o [Link](): Reads a line of strings.

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

You are David Blake


ar

The following code demonstrates the use of placeholders in the


ith

[Link]() method:
w

using System;
de

class Loan
{
co

static void Main(string[] args)


{
stringcustName;
doubleloanAmount;
float interest = 0.09F;
doubleinterestAmount = 0;
doubletotalAmount = 0;
[Link]("Enter the name of the customer : ");
custName = [Link]();
[Link]("Enter loan amount : ");
loanAmount = [Link]([Link]());
interestAmount = loanAmount * interest;
totalAmount = loanAmount + interestAmount;
[Link]("\nCustomer Name : {0}", custName);

pg. 29
DOTNET NOTES BY ASHOK PATE

[Link]("Loan amount : ${0:#,###.#0} \nInterest rate : {1:0#%} \nInterest Amount


: ${2:#,###.#0}",
loanAmount, interest, interestAmount );
[Link]("Total amount to be paid : ${0:#,###.#0} ", totalAmount);
}
}

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

along with the percentage sign.


.in
The following figure displays the example of placeholders:
ys
ra
ar
ith
w
de
co

Numeric Format Specifiers In C#


 Format specifiers are special characters that are used to display
values of variables in a particular format. For example, you can
display an octal value as decimal using format specifiers.
pg. 30
DOTNET NOTES BY ASHOK PATE

 In C#, you can convert numeric values in different formats. For


example, you can display a big number in an exponential form.
 To convert numeric values using numeric format specifiers, you
should enclose the specifier in curly braces. These curly braces must
be enclosed in double quotes. This is done in the output methods of
the Console class.

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

C, D, and E format specifiers:


ar

int num = 456;


[Link](“{0:C}”, num);
ith

[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

static void Main(string[] args)


{
double loanAmount = 15590;
float interest = 0.09F;
double interestAmount = 0;
double totalAmount = 0;
interestAmount = loanAmount * interest ;
totalAmount = loanAmount + interestAmount;
[Link](“Loan amount : ${0:#,###.#0} “, loanAmount);
[Link](“Interest rate : {0:0#%} “, interest);
[Link](“Total amount to be paid :${0:#,###.#0}”,totalAmount);
}
}

94
In Above Code,

21
The #, %, ., and 0 custom numeric format specifiers are used to

59

display the loan details of the customer in the desired format.

07
The following figure displays the example of custom numeric format

80
specifiers:
.in
ys
ra
ar
ith
w

Some More Number Format Specifiers


de

There are some additional number format specifiers that are described in
co

the following table:

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)
{

[Link]("Enter first number");


int num1 = [Link]([Link]());
pg. 35
DOTNET NOTES BY ASHOK PATE

[Link]("Enter Second number");


int num2 = [Link]([Link]());
int sum = num1 + num2;

[Link]("Addition result is: {0}", sum);


[Link]();

//[Link]("Enter your first Name ");


//string fname = [Link]();
//[Link]("Enter your Last Name ");
//string lname = [Link]();
//[Link]("Your Name is : " + fname + " " + lname); // concatenation

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

 A variable is used to store data in a program and is declared with an


ar

associated data type.


ith

 A variable has a name and may contain a value.


A data type defines the type of data that can be stored in a variable.
w


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

be stored in variables. Based on the type of data that needs to be


stored in a variable, variables can be assigned different data types.
.in
Using Variables
ys
ra

 In C#, memory is allocated to a variable at the time of its creation and


ar

a variable is given a name that uniquely identifies the variable within


its scope.
ith

 On initializing a variable, the value of a variable can be changed as


w

required to keep track of data being used in a program. When


de

referring to a variable, you are actually referring to the value stored in


that variable.
co

The following figure illustrates the concept of a variable:

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

 = Is the assignment operator used to assign values.


 value: Is the data that is stored in the variable.
w
de

The following code declares two variables, namely, empNumber and


empName:
co

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

 Values can be assigned to variables by using the assignment operator


(=), as follows:
o empNumber = 100;

o empName = “David Blake”;

 You can also assign a value to a variable upon creation, as follows:


o int empNumber = 100;

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

that results in faster memory allocation to variables of value types.


ar

 Most of the built-in data types are value types.


ith

 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

 The pre-defined data types are referred to as basic data types in C#


that have a pre-defined range and size.
 The size of the data type helps the compiler to allocate memory space
and the range helps the compiler to ensure that the value assigned, is
within the range of the variable’s data type.

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

represents a real world entity. The pre-defined and user-defined data


types are created based on the Object class.
String

pg. 40
DOTNET NOTES BY ASHOK PATE

 String is a built-in reference type that signifies Unicode character


string values. It allows you to assign and manipulate string values.
Once strings are created, they cannot be modified.
Class
 A class is a user-defined structure that contains variables and
methods. For example, the Employee class can be a user-defined

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

one or more methods.


Interface
.in
ys
 An interface is a user-defined structure that groups related
ra

functionalities which may belong to any class or struct.


ar

Array
ith

An array is a user-defined data structure that contains values of the


w

same data type, such as marks of students.


de

INTEGRAL TYPE - Integer DataType


co

Signed Integers (Which Takes Negative And Positive Values)


Unsigned Integers (Which Only Takes Positive Values)
 sbyte
 byte
 short
pg. 41
DOTNET NOTES BY ASHOK PATE

 ushort
 int
 uint
 long
 ulong
DataType, Its Range & Its Size

94
21
59
07
80
.in
ys
ra
ar
ith
w
de
co

2 Properties to get maximum & minimum value of data type


 MINVALUE PROPERTY
 MAXVALUE PROPERTY
Boolean Data Type

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

 Char stores single character at a time in a variable.


ra

 Single quotes will be used for char data type.


ar

Verbatim Literal
ith

Verbatim literal is a string with an @ symbol.


w

Verbatim literal make escape sequences translate as normal printable


de

characters to enhance readability.


co

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

Rules For Defining Variables


A variable needs to be declared before it can be referenced by following
certain rules as follows:
 A variable name can begin with an uppercase or a lowercase letter.
The name can contain letters, digits, and the underscore character (_).
The first character of the variable name must be a letter and not a

94

digit. The underscore is also a legal first character, but it is not

21
recommended at the beginning of a name.
C# is a case-sensitive language; hence, variable names count and

59

Count refer to two different variables.

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

 data type: Is a valid variable type.


ith

 variable name1, variable name2, variable nameN: Are valid variable


names or identifiers.
w
de

The following is the syntax to declare and initialize multiple variables:


co

<data <data type><variable name1> = <value1>, <variable name2> = <value2>;

The following code demonstrates how to declare and initialize


variables in C#:
bool boolTest = true;
short byteTest = 19;
int intTest;
string stringTest = “David”;
float floatTest;
int Test = 140000;

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

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.

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";

//int num1 = [Link](a);


.in
ys
//int num2 = [Link](b);
ra

int num1 = Convert.ToInt32(a);


ar

//int num2 = Convert.ToInt32(b);


ith

//int c = num1 + num2;


w

[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

Constants & Literals In C# Programming


A constant has a fixed value that remains unchanged throughout the
program while a literal provides a mean of expressing specific values in a
program.
Example

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

provided in the formula.

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

 A constant has a fixed value that remains unchanged throughout the


ith

program.
w

 In C#, you can declare constants for all data types.


de

 You have to initialize a constant at the time of its declaration.


 Constants are declared for value types rather than for reference
co

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

 A literal is a static value assigned to variables and constants.


 Numeric literals might suffix with a letter of the alphabet to indicate
w

the data type of the literal.


de

 This letter can be either in upper or lowercase.


co

Example
For example, in the following declaration,
string bookName = “Csharp”

Csharp is a literal assigned to the variable bookName of type string.


Types Of Literals
pg. 49
DOTNET NOTES BY ASHOK PATE

 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

o long val = 53L;


ith

 Where,
w

o 53L: Is an integer literal assigned to the variable val.


de

Real Literal
co

 Real Literal: A real literal is assigned to float, double (default), and


decimal data types. This is indicated by the suffix letter appearing
after the assigned value. A real literal can be suffixed by F, D, or M.
F denotes float, D denotes double, and M denotes decimal. For
example,
o float val = 1.66F;

 Where,
pg. 50
DOTNET NOTES BY ASHOK PATE

o 1.66F: Is a real literal assigned to the variable val.


Character Literal
 Character Literal: A character literal is assigned to a char data type. A
character literal is always enclosed in single quotes. For example,
o char val = ‘A’;

Where,

94

o A: Is a character literal assigned to the variable val.

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

o string email = null;


de

 Where,
o null: Specifies that e-mail does not refer to any objects
co

(reference).

--------------------------------------------------------------------------------------------

pg. 51
DOTNET NOTES BY ASHOK PATE

Date And Time Format Specifiers In C#


A date and time format specifier is a special character that enables you to
display the date and time values in different formats.
Example
 You can display a date in mm-dd-yyyy format and time in hh:mm

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

time in 12-hour and 24-hour formats.

80
 The following is the syntax for date and time format specifiers:
[Link](“{format specifier}”, <datetime object>);
.in
Where,
ys

formatspecifier: Is the date and time format specifier.


ra

 datetime object: Is the object of the DateTime class.


ar
ith

Format Specifier Name


d Short date
w

D Long date
f Full date/time (short time)
de

F Full date/time (long time)


g •General date/time (short time)
co

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

Full Date & Time Example .in


[Link]("{0:HH:mm:ss tt}", dt);
ys

[Link]("{0:dd-MM-yyyy}", dt);
ra

Using Standard Date and Time Format Specifiers


ar
ith

The following code demonstrates the conversion of a specified date and


time using the d, D, f, F, and g date and time format specifiers:
w
de

DateTimedt = [Link];
// Returns short date (MM/DD/YYYY)
co

[Link](“Short date format(d): {0:d}”, dt);


// Returns long date (Day, Month Date, Year)
[Link](“Long date format (D): {0:D}”, dt);
// Returns full date with time without seconds
[Link](“Full date with time without seconds (f):{0:f}”, dt);
// Returns full date with time with seconds
[Link](“Full date with time with seconds (F):{0:F}”, dt);
// Returns short date and short time without seconds
[Link](“Short date and short time without seconds (g):{0:g}”, dt);

Output

pg. 53
DOTNET NOTES BY ASHOK PATE

Short date format(d): 23/04/2007


Long date format (D): Monday, April 23, 2007
Full date with time without seconds (f):Monday, April 23, 2007 12:58 PM
Full date with time with seconds (F):Monday, April 23, 2007 [Link] PM
Short date and short time without seconds (g):23/04/2007 12:58 PM
The following code demonstrates the conversion of a specified date and

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

Short time (t):12:58 PM


ar

Short time with seconds (T):12:58:43 PM


ith

Year and Month (y):April, 2007


w

Custom DateTime Format Strings


de

Any non-standard DateTime format string is referred to as a custom


co

DateTime format string. Custom DateTime format strings consist of more


than one custom DateTime format specifiers. The following table lists
some of the custom DateTime format specifiers:

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

[Link]("Time with seconds: {0:HH:mm:ss tt}", date);


[Link]("Day of month: {0:m}", date);
ar

[Link]("Year: {0:yyyy}", date);


}
}
ith
w

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

Decision Making Statements In C#


• Is a programming construct supported by C# that controls the
flow of a program.
• Executes a particular block of statements based on a boolean
condition, which is an expression returning true or false.

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

• Nested Switch Case


ith

The If Statement
w
de

• The if statement allows you to execute a block of statements


after evaluating the specified logical condition.
co

• The if statement starts with the if keyword and is followed by


the condition.
• If the condition evaluates to true, the block of statements
following the if statement is executed.

pg. 56
DOTNET NOTES BY ASHOK PATE

• If the condition evaluates to false, the block of statements


following the if statement is ignored and the statement after the
block is executed.

94
21
59
07
80
.in
The If-else Statement
ys
ra

• In some situations, it is required to define an action for a false


ar

condition by using an if...else construct.


ith

• The if...else construct starts with the if block followed by an else


w

block and the else block starts with the else keyword followed by
de

a block of statements.
co

• If the condition specified in the if statement evaluates to false,


the statements in the else block are executed.
• The if…else…if construct allows you to check multiple conditions
to execute a different block of code for each condition.
• It is also referred to as if-else–if ladder.
pg. 57
DOTNET NOTES BY ASHOK PATE

• The construct starts with the if statement followed by multiple


else if statements followed by an optional else block.
• The conditions specified in the if…else…if construct are evaluated
sequentially.
• The execution starts from the if statement. If a condition

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

execution of the inner if statements. The compiler executes the


ar

inner if statements only if the condition in the outer if statement


ith

is true.
w

• In addition, each inner if statement is executed only if the


de

condition in its previous inner if statement is true.


co

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

• The switch…case statement is used when a variable needs to be


compared against different values.
• In C#, the flow of execution from one case statement is not
allowed to continue to the next case statement and is referred to
as the ‘no-fall-through’ rule of C#.

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

• Arithmetic operators are binary operators because they work


co

with two operands, with the operator being placed in between


the operands.
• These operators allow you to perform computations on numeric
or string data.
• +, - , / , * , % .
pg. 59
DOTNET NOTES BY ASHOK PATE

Relational Or Comparison Operators


• Relational operators make a comparison between two operands
and return a boolean value, true, or false.
• ==
• !=

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

Boolean Data Type


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
.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

 Difference between value type and reference types ?


de

Value Type Reference Type


co

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

 Diff bt stack and heap

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 was introduced in c# 4.0


ra

 Dynamic keyword is also used to store any type of data in its variable.
ar

 Value of dynamic variable is decided at run time.


ith

 Initialization is not mandatory when we declare a variable with dynamic


keyword.
w

 If we want to check the type of value which is stored in dynamic variable


de

then we can use gettype() method with the dynamic variable.


 When we initialize the dynamic variable with some value then we can
co

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

int num1 = 10; // int is value type


object obj1 = num1; // Implicit conversion of value type into reference type.
ar

 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

static void Main(string[] args) Static void PassByValue (int a)


{ 5 {
int value = 5; a = a + 10;

94
PassByValue(value); 15 [Link](“value is: ” + a);

21
[Link](value); }

59
}

07
80
PASS BY REFERENCE

Static void PassByRef (ref int a)


.in
static void Main(string[] args) {
ys

{ 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

static void Main(string[] args) Static void PassByOut (out int a)

{ {

int value; a = 20;

PassByOut(out value); [Link](“value is: ” + a);

[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

explicitly specify the ref keyword before the required parameters.


 The variables passed by reference from the calling method must be first
ar

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

 The variables passed by reference from the calling method


ith

must be first initialized.


w
de
co
94
21
59
07
80
.in
ys
ra

Pass By Reference
ar

The following syntax is used to pass values by reference


using the ref keyword.
ith
w

<access_modifier><return_type><MethodName> (ref parameter1, ref parameter2,


parameter3, parameter4, ...parameterN)
de

{
// 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

before the variables numValueOne and numValueTwo.


 In the Calculate() method, the multiplication and division
.in
operations are performed on the values passed as parameters
and the results are stored in the numValueOne and
ys
numValueTwovariables respectively.
ra

 The resultant values stored in these variables are also


ar

reflected in the numOne and numTwo variables respectively


as the values are passed by reference to the method
ith

Calculate().
w
de

The following figure displays the use of ref keyword: Output


co
Out Keyword
 The out keyword is similar to the ref keyword and causes
arguments to be passed by reference.
 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.

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

<access_modifier><return_type><MethodName> (out parameter1, out


parameter2, ...parameterN)
{
ith

// actions to be performed
}
w

where,
de

parameter 1…parameterN: Specifies that there can be any


co

number of parameters and it is not necessary for all the parameters


to be
out parameters.
The following code uses the out keyword to pass the
parameters by reference:
using System;
class OutParameters
{
static void Depreciation(out intval)
{
{
val = 20000;
intdep = val * 5/100;
intamt = val - dep;
[Link](“Depreciation Amount: “ + dep);
[Link](“Reduced value after depreciation: “ +
amt);
}
}
static void Main(string[] args)
{
int value;
Depreciation(out value);

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

Source Code Of Pass By Value, Pass By Reference & Out


Keywords
using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace REF_AND_OUT_KEYWORDS
{
class Program
{
//public static void PassByValue(int a)
//{
// a = a + 10;
// [Link]("Value is: {0}", a);
//}

//public static void PassByRef(ref 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
}

static void Main(string[] args)

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 as well as from other classes.


ith

The following code declares a public string variable called


w

Name to store the name of the person which can be publicly


de

accessed by any other class:


co

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

protected float Salary;


}
ith
w

internal: The internal access modifier allows the class members


de

to be accessible only within the classes of the same assembly. An


assembly is a file that is automatically generated by the compiler
co

upon successful compilation of a .NET application. The code


declares a variable called NumOne as internal, which means it has
only assembly-level access.
public class Sample
{
// Only accessible within the same assembly
internal static intNumOne = 3;
}
The following figure displays the various accessibility levels:

94
21
59
07
80
.in
ys
ra
ar

Protected Access Modifier


ith

 The protected access modifier protects the data members


w

that are declared using this modifier.


de

 The protected access modifier is specified using the


protected keyword.
co

 Variables or methods that are declared as protected are


accessed only by the class in which they are declared or by a
class that is derived from this class.
The following figure displays an example of using the
protected access modifier:
94
21
59
07
Protected Access Modifier

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

VariableName: Is the name of the variable.


ar

The following syntax declares a protected method:


ith

protected <return_type> <MethodName>(argument_list);


w

where,
de

return_type: Is the type of value the method will return.


co

MethodName: Is the name of the method.


argument_list: Is the list of parameters.
The following code demonstrates the use of the protected
access modifier:
class Animal
{
protected string Food;
protected string Activity;
}
class Cat:Animal
{
static voidMain(String[]args)
{
cat objCat=newCat();
[Link]="Mouse";
[Link]="lazearound";
[Link]("The Cat loves to eat"+[Link]+".");
[Link]("The Catloves to"+[Link]+".");
}

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

Cat loves to eat Mouse.


ith

The Cat loves to laze around


w
de
co
What Is Constructor In C# ?
 A Constructor is used to initialize objects.
 Constructors can initialize the variables of a class or perform
startup operations only once when the object of the class is
instantiated.
 A class constructor is a special member function of a class
that is executed whenever we create new objects of that class.

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

it does not have any return type.

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

It is possible to specify the accessibility level of constructors


ra

within an application by using access modifiers such as:


ar
ith

 public: Specifies that the constructor will be called whenever


a class is instantiated. This instantiation can be done from
w

anywhere and from any assembly.


de

 private: Specifies that this constructor cannot be invoked by


co

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

instance of the Circle class attempts to invoke the constructor


which is declared as private. This is an illegal attempt.
.in
 Private constructors are used to prevent class instantiation.
ys
 If a class has defined only private constructors, the new
keyword cannot be used to instantiate the object of the class.
ra

 This means no other class can use the data members of the
ar

class that has only private constructors.


ith

 Therefore, private constructors are only used if a class


contains only static data members.
w

This is because static members are invoked using the class


de

name.
co

The following figure shows the output for creating a class


Circle with a private constructor:
The following code used to initialize the values of _empName,

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

A constructor is created for the class Employees. When the


de

class is instantiated, the constructor is invoked with the


co

parameters John and 10.


 These values are stored in the class variables empName and
empAge respectively. The department of the employee is
then displayed in the console window.
Source Code Of Constructor
using System;
using [Link];
using [Link];
using [Link];
using [Link];

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

static void Main(string[] args)


{
ar

Employees Ali = new Employees(11,"Ali Khan",22);


Employees Zain = new Employees(12, "Zain Ali", 21);
ith

[Link]("Employee Id is {0}",[Link]());
[Link]("Employee Name is {0}", [Link]());
w

[Link]("Employee Age is {0}", [Link]());


[Link]("--------------------");
de

[Link]("Employee Id is {0}", [Link]());


[Link]("Employee Name is {0}", [Link]());
[Link]("Employee Age is {0}", [Link]());
co

[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

 We cannot call static constructor directly.


ith
w
de
co
CONSTRUCTORS IN C#
 A Constructor is used to initialize objects.
 A class constructor is a special member function of a class that is
executed whenever we create new objects of that class.
 A constructor has exactly the same name as that of class and it
does not have any return type.
Default Constructor
A constructor which has not defined any parameters or we can say

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.

In c#, Copy Constructor is a parameterized constructor which contains a


parameter of same class type. The copy constructor in C# is useful
whenever we want to initialize a new instance to the values of an

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:

 One use of a private constructor is when we have only static


members.
 Once we provide a constructor that is either private or public or

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

Following are the features of destructors:


ith

 Destructors cannot be overloaded or inherited.


w

 Destructors cannot be explicitly invoked.


de

 Destructors cannot specify access modifiers and cannot take


parameters.
co

The following code demonstrates the use of destructors:


using System;

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

 The destructor ~Employee is created having the same name


ar

as that of the class and the constructor.


The destructor is automatically called when the object
ith

objEmp is no longer needed to be used.


w

 However, you have no control on when the destructor is


de

going to be executed.
co

Source Code Of Destructors In C#


using System;
using [Link];
using [Link];
using [Link];
using [Link];

namespace DESTRUCTORS
{
class person
{
public string Name;
public int Age;

public person(string Name, int Age)


{
[Link] = Name;
[Link] = Age;
}

public string getName()


{
return [Link];
}
public int getAge()
{

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

3. MULTI CAST DELEGATES:


ar

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

than one function at a time. They are derived from


co

[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

 Auto implemented properties


ar
ith
w
de
co
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#.
 Properties in C# allow you to set and retrieve values of
fields declared with any access modifier in a secured

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

 Consider fields that store names and IDs of employees.


w

 You can create properties for these fields to ensure


de

accuracy and validity of values stored in them.


co

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

 Read only properties

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

access_modifier: Defines the scope of access for the


ith

property, which can be private, public, protected, or


w

internal.
de

 return_type: Determines the type of data the property will


co

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

when the property is assigned a new value using the equal

59
to (=) operator.
This value is stored in the private field by an implicit

07

parameter called value (keyword in C#) used in the set

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

property EmployeeName using the dot (.) operator to

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

 This invokes the get accessor, which returns the assigned


employee name. This invokes the set accessor, where the
ar

value keyword assigns the value to _empName.


ith

Output
w
de

Employee Name: Patrick Johnson


co

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
}
}

The following code demonstrates how to create a read-only


property.

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

[Link]("Book Name: " + [Link]);


[Link]("Book ID: " + [Link]);
ar

}
}
ith

In Above Code,
w
de

 The Books class creates two read-only properties that


returns the name and ID of the book.
co

 The class BookStore defines a Main() method that creates


an instance of the class Books by passing the parameter
values that refer to the name and ID of the book.
 The output displays the name and ID of the book by
invoking the get accessor of the appropriate read-only
properties.
Output
Book Name: Learn C# in 21 Days
Book ID: 10015
Write-Only Property
 The write-only property allows you to change the value of a

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 string DeptName{


set { _deptName = value; }
de

}
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

The read-write property allows you to set and retrieve the


ra

value of a private field. To create a read-write property, you


ar

should define the set and get accessors.


ith

The following syntax creates a read-write property.


w
de

<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

 The class Product creates a read-write property Price that


assigns and retrieves the price of the product based on the if
w

statement.
de

 The Goods class defines the Main()method that creates an


co

instance of the class Product by passing the values as


parameters that are name and ID of the product.
 The Display() method of the class Product is invoked that
displays the name, ID, and price of the product.
Output
Product Name: Hard Disk
Product ID: 101
Price: 345.25$
Properties can be further classified as static, abstract, and
boolean properties.

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

belongs to the class rather than just an instance of the class.


ra

 The static property is used by a programmer without


ar

creating an instance of the class.


ith

 The static property is used to access and manipulate static


fields of a class in a safe manner.
w
de

The following code demonstrates a class with a static


property.
co

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 UniversityName and DepartmentName of the


ra

class University by using the dot (.) operator.


ar

 This initializes the static fields of the class by invoking the


ith

set accessor of the appropriate properties.


The code displays the name of the university and the
w

department by invoking the get accessor of the appropriate


de

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 DimensionOne {


set;
w

}
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

overrides the two abstract properties DimensionOne and


DimensionTwo by setting appropriate dimension values for
ar

the rectangle.
ith

 The Area() method calculates the area of the rectangle.


w

 The Main() method creates an instance of the derived class


de

Rectangle.
This instance invokes the properties, DimensionOne and
co

DimensionTwo, which, in turn, invokes the set accessor of


appropriate properties to assign appropriate dimension
values.
 The code displays the area of the rectangle by invoking the
Area() method of the Rectangle class.
Output
Area of Rectangle: 84.66
Boolean Properties
 A boolean property is declared by specifying the data type
of the property as bool.

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

public string lastName { get; private set; }


ith

public Student(string fname, string lname)


{
firstName = fname;
w

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]();
}
}
}

Source Code Of Abstract Properties

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
}

class student : person


{ .in
uint StudentId;
string StudentName;
ys
public override uint Id
{
ra

set
{
ar

if (value == 0)
{
ith

[Link]("Id cannot be Zero !!");


}
else
w

{
[Link] = value;
de

}
co

}
get
{
return [Link];
}

public override string Name


{
set
{
if([Link](value))
{
[Link]("Name cannot be null or empty !!");
}
else
{
[Link] = value;
}

}
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

Source Code Of Static Properties


ar

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;

public static string _UniversityName


{
set
{
if ([Link](value))
{
[Link]("You cannot enter null or empty value in
University NAme !!");
}
else
{
UniversityName = value;
}
}

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

static void Main(string[] args)


{
de

university._UniversityName = "Mehran University Jamshoro";


university._DepartmentName = "Software Engineering";
[Link]("University Name is:
co

{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

Int rollNo; [Link] String name;


ys
String name;
Int rollNo;
ra

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

1 Static Variable Used With


ar

Every Object, No Separate


Umar
Copy will be shared
ith
w

String SchoolName;
Ali
de
co

Zain

Note: class members can be fields, methods, properties, events,


indexers, constructors.
Arrays In C#
 An array is a list of items or collection of elements which is of
same or similar data type (homogenous elements).
 An array is a collection of elements of a single data type stored
in adjacent memory locations.
An array is a collection of related values placed in contiguous

94

memory locations and these values are referenced using a

21
common array name.
An array simplifies the task of maintaining these values

59

 An array always stores values of a single data type.

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

stands for the total number of elements in the array.


This arrangement of storing values helps in efficient storage of
ith

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

 An array declaration specifies the type of data that it can hold


and an identifier.
This identifier is basically an array name and is used with a

94

subscript / index to retrieve or set the data value at that

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

 data_type: Specifies the data type of the array elements (for


ith

example, int and char).


arrayName: Specifies the name of the array.
w


de

Initializing Arrays
co

An array can be:

 Created using the new keyword and then initialized.


 Initialized at the time of declaration itself, in which case the new
keyword is not used.
Creating and initializing an array with the new keyword involves
specifying the size of an array.

The number of elements stored in an array depends upon the


specified size.

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

The following syntax is used to create an array:


co

type[] arrayName = new type[size-value];

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.

The following code creates an integer array which can have


a maximum of five elements in it:

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

 val1: It is the value of the first element.


valN: It is the value of the nth element.
ith


w

Example:
de

public string[] studNames = new string{“Allan”, “Wilson”, “James”, “Arnold”};


co

Using The Foreach Loop For Arrays


The foreach loop:

 In C# is an extension of the for loop.


 Is used to perform specific actions on large data collections and
can even be used on arrays.
 Reads every element in the specified array.
 Allows you to execute a block of code for each element in the
array.
 Is particularly useful for reference types, such as strings.

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

static void Main(string[] args)

{
w
de

//string[] myArray = { "Adil", "Zubia", "Sameed", "Ammad" };


co

//[Link]([Link]);

//for (int i = 0; i < [Link]; i++)

//{

// [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

[Link]("How many names you want to store ??");


ith

int size = [Link]([Link]()); // 5


w
de

string[] names = new string[size];


co

for (int i = 0; i < size; i++)

[Link]("Enter Data: ");

string name = [Link]();

names[i] = name;
}

[Link]("----------------");

foreach (string name in names)

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

//[Link]("Foreach loop terminates..");


de

//for(int i = 0; i < [Link]; i++)

//{
co

// [Link](names[i]);

//}

// 2 types of arrays
// single dimensional array

// multi dimensional array

//string[] names = new string[3];

//names[0] = "Abdul Rehman";

//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

// foreach loop - arrays


ar
ith
w
de

//int[] nums = new int[3];


co

//nums[0] = 11;

//nums[1] = 22;

//nums[2] = 33;

//nums[3] = 44;
//[Link](nums[2]);

//comment - ctrl + k, ctrl + c

//uncomment - ctrl + k, ctrl + u

[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.

 If a class is declared abstract, it cannot be instantiated.

 Abstract class is used only as a base class.

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

 Instead of curly braces, an abstract method will have a semi colon


ra

(;) at the end.


ar

 Abstract keyword is used to declare the method as abstract.


ith

 You have to place the abstract keyword before the method name
in the method declaration.
w

 If a class has any abstract method, whether declared or inherited,


de

the entire class must be declared as abstract.


co

 If you want a class to contain a particular method but you want


the actual implementation of that method to be determined by
child classes, you can declare the method in the parent class as an
abstract.
Inheritance In C# Programming
 The similarity in physical features of a child to that of its parents is
due to the child having inherited these features from its parents.
 Similarly, in C#, inheritance allows you to create a class by
deriving the common attributes and methods of an existing class.
 Inheritance provides reusability by allowing us to extend an
existing class.
 The reason behind OOP programming is to promote the

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

VISITING EMPLOYEES PERMANENT EMPLOYEES


ar
ith

Int EmpId; Int EmpId;


String EmpName; String EmpName;
w

Int EmpAge; Int EmpAge;


de

Int EmpContactNo; Int EmpContactNo;


Int visitingSalary; Int permanentSalary;
co

Int visitingHours; Int permanentHours;


94
21
59
07
80
 The following are the types of inheritance in C#.
.in
ys
ra
ar
ith
w
de
co

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

The similarity in physical features of a child to that of its


co

parents is due to the child having inherited these features


from its parents.
 Similarly, in C#, inheritance allows you to create a class by
deriving the common attributes and methods of an existing
class.
 The class from which the new class is created is known as
the base class and the created class is known as the
derived class.
 The process of creating a new class by extending some
features of an existing class is known as inheritance.

94
21
59
07
80
.in
ys
ra
ar
ith
w

Example
de
co

 Consider a class called Vehicle that consists of a variable


called color and a method called Speed().
 These data members of the Vehicle class can be inherited by
the TwoWheelerVehicle and FourWheelerVehicle classes.
The following figure illustrates an example of inheritance:
94
21
59
Inheritance In C#

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

 The reason behind OOP programming is to promote the


ith

reusability of code and to reduce complexity in code and it is


possible by using inheritance.
w
de
co
94
21
59
07
Purpose Of Inheritance

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

 Consider a class named Animal which defines attributes and


behavior for animals.
w

 If a new class named Cat has to be created, it can be done


de

based on Animal because a cat is also an animal.


Thus, you can reuse the code from the
co

previously-defined class.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de

Apart from reusability, inheritance is widely used for:


co

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

derived class by creating more methods and attributes that

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

The inheritance concept is based on a base class and derived class.


Let us see the definition of a base and derived class.
ar
ith

 BASE CLASS - is the class from which features are to be


inherited into another class.
w

DERIVED CLASS - it is the class in which the base class


de

features are inherited.


co
Constructor In Inheritance
 A constructor is a method with the same name as the class name
and is invoked automatically when a new instance of a class is
created.
 Constructors of both classes must be executed when the object of
child class is created.
 Derived Class’s constructor invokes constructor of Base class.
 Explicit call to the super class constructor from sub class’s can be
made using base().

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

 Invoke the derived class data members.


ith

 Access the base class members using the base keyword.


w

The following syntax shows the use of the base keyword:


de

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

 In C# you can invoke the base class constructor by either


w

instantiating the derived class or the base class.


de

 In C# you can invoke the constructor of the base class


followed by the constructor of the derived class.
co

 In C# you can invoke the base class constructor by using the


base keyword in the derived class constructor declaration.
 In C# you can pass parameters to the constructor.
 However, C# cannot inherit constructors similar to how you
inherit methods.
The following figure displays an example of constructor
inheritance:

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

[Link]("Animal constructor with a string parameter");


de

}
}
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

the constructor of the class Animal that does not contain

21
parameters is invoked.
In the class Details, when the derived class constructor is

59

invoked, it will in turn invoke the parameterized constructor

07
of the base class.

80
Output
Animal constructor with a string parameter .in
Derived Canine
ys

Invoking Parameterized Base Class Constructors


ra

The derived class constructor can explicitly invoke the base


ar

class constructor by using the base keyword.


ith

 If a base class constructor has a parameter, the base keyword


w

is followed by the value of the type specified in the


de

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

 In the Main()method, when an instance of the Automobiles


ra

class is created, it invokes the constructor of the Metals


ar

class, followed by the constructor of the SteelCompany


ith

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

 BASE CLASS - is the class from which features are to be


ar

inherited into another class.


DERIVED CLASS - it is the class in which the base class
ith

features are inherited.


w

Single Inheritance In C#
de
co

It is the type of inheritance in which there is one base class and


one derived class.
94
Single Inheritance In C#

21
Source Code Of Single Inheritance

59
using System;

07
using [Link];
using [Link];
using [Link];

80
using [Link];

namespace INHERITANCE_CSHARP
{

class PermanentEmployees : Employees


.in
ys
{

public int permanentSalary;


ra

public int permanentHours;


}
ar

class Employees
{
ith

public int EmpId;


public string EmpName;
public int EmpAge;
w

public int EmpContactNo;


de

public void show()


{
co

[Link]("This is a method of base class !!");


}

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

classes derived from one base class.

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

inherits all the attributes of the Animal class.


The class Dog is inherited from the class Mammal and
ar

inherits all the attributes of both the Animal and Mammal


ith

classes.
w

The following figure depicts multi-level hierarchy of related


de

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

Every animal eats something.


Mammals give birth to young ones.
Dog Barks.
Polymorphism In C#
 Polymorphism is one of the four pillars of Object Oriented
Programming.
 Polymorphism in C# is a concept by which we can perform a single
action by different ways.
 Polymorphism is derived from 2 Greek words: POLY and MORPHS.
 The word "poly" means many and "morphs" means forms.
 So polymorphism means many forms.
Real World Example

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

In the derived class, you need to declare the inherited


ar

virtual method using the override keyword.


ith

In the derived class, you need to declare the inherited


w

virtual method using the override keyword which is


de

mandatory for any virtual method that is inherited in the


co

derived class.
The override keyword overrides the base class method in
the derived class.
Difference Between Method Hiding And Method Overriding In C#

METHOD HIDING METHOD OVERRIDING

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

constructor will have different signatures.

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

public Rectangle(double len, double wide)


{
_length = len;
co

_breadth = wide;
}

public double Area()


{
return _length * _breadth;
}
static void Main(string[] args)
{
Rectangle objRect1 = new Rectangle();
[Link](“Area of rectangle = “ + [Link]());
Rectangle objRect2 = new Rectangle(2.5, 6.9);
[Link](“Area of rectangle = “ + [Link]());
}
}

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

Source Code of Constructor Overloading


ar
ith

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));
}

static void Main(string[] args)

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

must be declared abstract.


 If a class is declared abstract, it cannot be instantiated.
ith

 To use an abstract class, you have to inherit it from another class,


w

provide implementations to the abstract methods in it.


de

 If you inherit an abstract class, you have to provide


co

implementations to all the abstract methods in it.


 An abstract class can implement code with non-Abstract methods.
 An Abstract class can have modifiers for methods, properties etc.
 An Abstract class can have constants and fields.
 An abstract class can implement a property.
 An abstract class can have constructors or destructors.
co STUDENT
de
w
ith
ar
PERSON

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

 In C#, by default, all members declared in an interface have public as the


ar

access modifier. They don’t allow explicit access modifiers.


ith

IMPLEMENTING AN INTERFACE
 An interface is implemented by a class in a way similar to inheriting a class.
w

 When implementing an interface in a class, implement all the abstract


de

methods declared in the interface. If all the methods are not implemented,
co

the class cannot be compiled.


 The methods implemented in the class should be declared with the same
name and signature as defined in the interface.
94
21
59
07
80
.in
ys
ra
ar
ith
w
de
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

prevent any change in its variables and methods.


ar
ith
w
de
co
Sealed Class & Sealed Methods In C#
Sealed Class

A sealed class is a class that prevents inheritance.

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

inherited by any other class.


 If a class tries to derive a sealed class, the C# compiler
.in
generates an error.
ys

Purpose of Sealed Classes


ra
ar

 Consider a class named SystemInformation that consists of


ith

critical methods that affect the working of the operating


system.
w

 You might not want any third party to inherit the class
de

SystemInformation and override its methods, thus, causing


co

security and copyright issues.


 Here, you can declare the SystemInformation class as
sealed to prevent any change in its variables and methods.
The following syntax is used to declare a sealed class:
sealed class<ClassName>
{
//body of the class
}

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

 The class Product is declared as sealed and it consists of


two variables.
co

 The class Goods contains the code to create an instance of


Product and uses the dot (.) operator to invoke variables
declared in Product.
The class Pen tries to inherit the sealed class Product, the C#
compiler generates an error, as shown in the following
figure:

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

unexpected functioning of the class.


.in
o When you want to prevent any third party from

modifying your class.


ys
ra

Source Code Of Sealed Class


ar

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 ChildClass : ParentClass


{
public void Show2()
{
[Link]("This is the method of child 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

override keyword with the sealed keyword.


ra
ar

Steps To Remember For Sealed Methods:


ith

 Sealed method is always an override method of child class.


w

 We cannot again override the sealed method.


de

 Sealed method is only available with Method Overriding.


 Sealed keyword is not available with the method hiding.
co

 Sealed is used together with override method.


 We cannot make normal methods as sealed.
The following syntax is used to declare an overridden
method as sealed:
sealed override <return_type> <MethodName>() { }
where,
 return_type: Specifies the data type of value returned by
the method.
 MethodName: Specifies the name of the overridden
method.
The following code declares an overridden method Print() as

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

static void Main (string [] args)


{
SealedSystem objSealed = new SealedSystem();
co

[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

Source Code Of Sealed Method


w
de

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]();

//C obj = new C();

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

 To associate a delegate with a particular method, the method must have


the same return type and parameter type as that of the delegate.
ar
ith
w
de
co
Method Hiding In C# Programming
 Method hiding occurs in inheritance relationship when base class and derived
class both have a method with same name and same signature.
 When we create the object of derived class it will hide the base class method
and will call its own method and this is called method hiding or name hiding in
C# inheritance.
 We use “new” keyword in derived function name to show that
implementation of the function in derived class is intentional and derived class
no longer want to use base class method.

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.

Do not contain any methods for Contain methods for operations on


operations on elements. elements.

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

 We can never insert a value into a middle of an array, because if we want to


w

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

 We can never delete a value from a middle of an array.


co

 Accessing collections is similar to accessing arrays, where elements are


accessed by their index numbers. However, there are differences between
arrays and collections in C#.
 Collections were introduced in C# 1.0
 We have two kinds of Collections.
o Non-Generic collections
 Stack, ArrayList, Hashtable, SortedList etc.
 [Link] namespace have non-generic
collections.
o Generic collections.
 List<T>, LinkedList<T>, Queue<T>,SortedList<T,V>.
 [Link] namespace have generic
collections.

94
21
59
07
80
.in
ys
ra

 Collections have a mechanism called auto-resizing.


ar

 Capacity property which tells number of items that can be stored under any collection.
 INSERT METHOD.
ith

 REMOVE AND REMOVEAT METHOD.


w
de
co
Constants & Literals In C# Programming
A constant has a fixed value that remains unchanged throughout
the program while a literal provides a mean of expressing
specific values in a program.
Example

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

must be provided in the formula.

59
 The value of pi is a constant value.
This value will remain unchanged irrespective of the value

07

of the 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
ys
them later or to prevent any modification to the values.
ra

Constants In C#
ar
ith

 A constant has a fixed value that remains unchanged


w

throughout the program.


de

 In C#, you can declare constants for all data types.


 You have to initialize a constant at the time of its
co

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

[Link](“Area of the circle is ” + area);


ith

In Above Code,
w

 A constant called _pi is assigned the value 3.14, which is a


de

fixed value. The variable, radius, stores the radius of the


circle. The code calculates the area of the circle and
co

displays it as the output.

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

 Boolean Literal: Boolean literals have two values, true or


w

false. For example,


de

o bool val = true;

where,
co

o true: Is a Boolean literal assigned to the variable val.

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

Character Literal: A character literal is assigned to a char


ra

data type. A character literal is always enclosed in single


ar

quotes. For example,


ith

o char val = ‘A’;


w

 Where,
de

o A: Is a character literal assigned to the variable val.


co

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

 Increases the reusability of the code.


 Generic has a performance advantage because it removes the
possibilities of boxing and unboxing.
GENERIC METHODS
Generic methods process values whose data types are known only
when accessing the variables that store these values.
A generic method is declared with the generic type parameter list
enclosed within angular brackets.
Defining methods with type parameters allow you to call the method
with a different type every time.
You can declare a generic method within generic or non-generic class

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.

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


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

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]

You might also like