Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
33% found this document useful (3 votes)
2K views

Awp Unit-1 Notes

The document discusses topics related to the .NET framework including: 1. An overview of components of the .NET framework such as the common language runtime, class libraries, assemblies, and garbage collector. 2. Design goals of the .NET framework including simplifying development, unifying programming models, leveraging standard web protocols, and simplifying deployment. 3. Explanations of specific .NET framework components such as building block services, class libraries, and the common type system.

Uploaded by

Francis Xavier
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
33% found this document useful (3 votes)
2K views

Awp Unit-1 Notes

The document discusses topics related to the .NET framework including: 1. An overview of components of the .NET framework such as the common language runtime, class libraries, assemblies, and garbage collector. 2. Design goals of the .NET framework including simplifying development, unifying programming models, leveraging standard web protocols, and simplifying deployment. 3. Explanations of specific .NET framework components such as building block services, class libraries, and the common type system.

Uploaded by

Francis Xavier
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

T.Y.BSc(I.

T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

1. Review of Dot Net Framework

UNIT – I

 Review of .NET frameworks, Introduction to C#, Variables and


expressions, Flow controls, functions, debugging and error handling,
OOPs with C#, Defining classes and class members.

 Assembly, Components of Assembly, Private and Shared Assembly,


Garbage Collector, JIT compiler. Namespaces

Under this Chapter the topics are:


• What is .NET
• The .NET framework
• Components of .NET framework
• Design Goals of .NET framework
• .NET Enterprise Servers
• .NET Building Block Services
• Visual Studio.NET
• Highlights of .NET framework
• CTS
• Metadata
• CLS (Common Language Specification)
• CLR (Common Language Runtime)
• VES (Virtual Execution System)
• Assemblies
• Garbage Collector
• JIT Compiler

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Q.: Explain .NET Framework

 Microsoft .NET is much more than XML Web services.

 At the heart of Microsoft .NET is the .NET Framework, consisting of the common
language runtime and the class libraries.

 These two components provide the execution engine and programming APIs for
building .NET applications.

 Applications compiled for the .NET Framework are not compiled directly to native
code. Instead, they are compiled to an intermediate language called Microsoft
Intermediate Language (MSIL).

 When an application is run for the first time, the common language runtime just-
in-time compiler compiles the MSIL code into native code before it is executed.

 The common language runtime is more than a simple JIT compiler; it is also
responsible for providing low-level execution services, such as
 garbage collection,
 exception handling,
 security services, and
 runtime type-safety checking.

 Because of the common language runtime's role in managing execution, programs


that target the .NET Framework are sometimes called "managed" applications.

 The .NET Framework also includes a set of classes for building applications that
run on the common language runtime.

 These class libraries provide rich support for a wide range of tasks, including data
access, security, file IO, XML manipulation, messaging, class reflection, XML Web
services, user-interface construction, text processing, ASP.NET, and Microsoft
Windows services.

 The most unique attribute of the .NET Framework is its support for multiple
languages.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

 It provides support for over 20 programming languages including Perl, Python,


and COBOL.
 Relying on the common language runtime, code compiled with these compilers
can interoperate.

 The .NET Framework is composed of the four extended applications named as


four blue boxes—representing
1. ASP.NET,
2. Windows Forms,
3. ADO.NET and
4. XML, and subcomponents.

Fig: Dot Net Framework


Source: www.msdn.microsoft.com

Q.: Explain Components of .Net Framework

The various components of the .Net framework 3.5. The following table describes the
components of the .Net framework 3.5 and the job they perform:
Common Language Runtime:
It is built around CTS. It performs runtime tasks like memory management and garbage
collection.
Base Class Libraries:
It is a rich set of functional base classes.
Extended Class Libraries:
Extended from base class libraries and designed to make it easier and faster to develop
a specific application.
CLS: (Common Language Specification)

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

It defines requirements for .net languages. It contains the specifications for the .Net
supported languages and implementation of language integration.
CTS: (Common Type System)
It provides guidelines for declaring, using and managing types at runtime and cross-
language communication.

Metadata and Assemblies:


Metadata is the binary information describing the program, which is either stored in a
portable executable file(PE) or in the memory. Assembly is a logical unit consisting of
the assembly manifest, type metadata, IL code and a set of resources like image files.
Multiple programming languages:
It provides unified programming model for several languages.
Visual Studio .net:
It is the IDE for coding with .net framework that spans the entire .net framework.

Windows & COM+ services:


Today’s requirements for today’s .net framework SDK is Windows and COM+ services
which provides facility to access the lower level system functionality.

the class framework encapsulates the following functionality:


• Data Access
• Thread management
• Interoperability with unmanaged code
• Network protocol support
• XML support
• Web services support and Windows Forms support
• Access to assembly meta data

Q.: Explain design goals of the .NET framework


1. Simplify software development
2. unify programming models
3. leverage standard web protocols
4. simplify code deployment and maintenance

Simplify software development


a) Provide rich functional base classes that are extensible and easier to access than
standard windows API calls.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

b) Support XML web services.


Unify programming models
a) All .NET languages must provide the same set of .NET framework classes and services
as outlined in the CLS. They must be interoperable.
Leverage standard web protocols
a) Deep XML support.
b) XML based grammars are used throughout.
Simplify code deployment and maintenance
i) Eliminate “DLL hell”
ii) Simplify deployment and versioning of components.
iii) Provide richer compilers and runtime support
.
Q.: .NET Building Block Services:

 The building blocks are web services themselves, so they can operate as stand-
alone components, or in collaboration with other components.
 As web services, they are programmable, and can be easily called from a
custom application.
 In contrast, ActiveX controls must be included within a Windows Application at
design time, and compiled directly into the runtime executable.
 The .NET building block services will include:
• Authentication-builds on Microsoft’s passport and Windows authentication
technologies.
• Enables developers to authenticate a user behind-the-scenes, and give them
access to private content without bothering them to log in manually every
time they access a new application
• This authentication service will be available in the future Operating System,
code named Blackcomb.
• Notification and Messaging-provides integrated messaging capabilities for any
device, including instant messaging and e-mail.
• Directory and Search – director y search services, for locating people and
finding information.
• Calendar- This service provides time management and scheduling services for
your application.
• XML store-provides an addressable location on the Internet for storing data.
The data is stored as XML, and is delivered using SOAP. XML data stores
provide you with a single data store that can be accessed by all of your devices.

Q.: Explain class library

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Class Libraries:
• The .NET framework classes are similar in concept to MFC, namely, they
provide developers with access to a wide range of system services without
having to do a lot of coding.
• The framework classes are organized into namespaces, which organize classes
into a hierarchical structure of related groups. For example, the System. Data
namespace contains a set of classes that provide data access functionality.
• The .NET framework provides classes at different levels of abstraction. At the
lowest level, the base class library provides a rich set of base classes that give
you easy access to Windows API functionality.
• Extended Class Libraries are nothing but abstracted classes that are focused
on one aspect of development: ASP .NET (For web services), ADO .NET (For
data access), XML (to parse and manipulate documents) and Windows Forms
(for windows based applications).
• CLS defines the requirements for .NET languages.

Q.: Explain Common Type System (CTS)

 CTS defines standard, object oriented types and value types that are
supported by all .NET programming languages.
 The CTS standards are what allow .NET to provide a unified programming
model, and to support multiple languages.
 A CTS is the first prerequisite to allowing languages to interoperate.
 This is easy to understand, if you consider that languages can only
interoperate if they are based on the same system of types.
 In the past, type discrepancies have caused many interoperability problems,
particularly for VB developers.

 So, CTS is an important new feature in the .NET framework. The CTS
must support a range of languages, some of which are object-oriented,
and some of which are not. Much has been made of the fact that
COBOL is now a first class .NET language. COBOL is a procedural
language, not an object-oriented one. The CTS provides two main types:
• Value Types
• Reference Types

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Value types are further classified into


 built-in types
 user defined types
Reference types are further classified into
 Pointers
 Objects
 Interfaces

 Value types are simple data types that roughly correspond to simple bit
patterns like integers and floats.
 In .NET, a value type derives from the System. Object amespace, and
supports an interface that provides information about the kind of data that
is stored, as well as the data value.
 They are useful for representing simple data types, and nay not-object user
defined type, including enumerations.
 They are known as exact types which mean that they fully describe the
value they hold.
 Reference types are also derived from the system.
 Object namespace, and may hold object references.
 They are self typing, which means that they describe their own interface.
 They are very specific to the type of object you are assigning.
 Once the reference is assigned, you expect to query the object reference
according to what its interface provides.

Some of the primitive data types are:


 Bool
 Char
 int 8
 int 16
 float 32
 float 64
 unsigned int8
 unsigned int16

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Type Safety:
 The CTS promotes type safety, which in turn improves code stability.
 In .NET, type safety means that type definitions are completely known, and
cannot be compromised.
 The CTS ensures that object references are strongly typed.
 It checks whether the array index out of range or not, whether the
arithmetic exceptions are handled properly or not etc.

Q.: Explain Meta Data:

Meta Data is organized information that the CLR uses to provide compile
time and runtime services, including:

 Loading of class files


 Memory Management
 Debugging
 Object Browsing
 MSIL translation no Native Code

NET components are self describing, because the Meta Data is stored as part of
the compiled component known in .NET as an assembly. Combine this with the
fact that .NET components do not require windows registry entries, and you can
immediately appreciate why deployments are so much easier in .NET.

The figure below illustrates different Meta Data Consumers:

reflection
designers
debugger
profiler

Proxy generator

Meta Data Code

Schema serialization
Type Other IL Generator
Browser Compilers

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

CONTENTS OF META DATA

 Description of the assembly(the deployment unit)


 identity: name, version and culture
 dependencies (other assemblies)
 security permission that the assembly requires to run
 Description of the Types
 Base classes and interfaces
 Custom attributes
 defined by the User
 defined by the Complier
 defined by the Framework

Meta data is language-independent.NET supported language access the same meta


data,and can interpret it the same way,Recall that Visual studio.NETallows you to mix
and match source code files from different language within the same project.
Meta data may also store custom attributes, some of which may be language-specific.
For example, C++ header information may be stored in meta data. This information is
ignored, unless you are loading the component files into C++.

Q.: EXPLAIN COMMON LANGUAGE SPECIFICATION (CLS)

The purpose of the NET framework is to define standards that makes it easier
it easier to write robust, secure and reusable code. The NET framework extends this
concept by allowing any language to participate in the framework; so long as it
conforms to the specifications embodied by the common Type System and the common
Language Specification.
The common language Specification (CLS) defines conventions that languages
must support in order to be interoperable within NET. The CLS defines rules that range
from naming conventions for interface members, to rules governing method
overloading.
In order to provide interoperation, a CLS- compliant language must obey the
following conventions:
 Public identifiers are case- sensitive.
 Language must be able to resolve identifiers that are equivalent to their
keywords.
 Stricter overloading rules; a given method name may refer to any number
of methods, as long as each one differs in the number of parameters, or
argument types.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

 Properties and events must follow strict naming rules.


 All pointers must be managed, and reference must be typed; otherwise,
they cannot be verified.

Q.: Explain CLR and its design goal:


• The CLR provides a rich level of support that simplifies application
development and provides for better code reuse.
• The CLR provides a broad set of runtime services, including compilation,
garbage collection and memory management.
• The CLR is built around the CTS, which defines standard, object-oriented
data types that are used across all .NET programming languages.
• Code that runs under the control of the CLR is called managed code.
Managed code allows the CLR to do the following.
1. Read meta data that describes the component interfaces and types
2. walk the code stack
3. handle exceptions
4. retrieve security information
Design Goals of the CLR:

1. Simplify Development
• Define standards that promote code reuse
• provide a broad range of services, including memory management and
garbage collection
2. Simplify application deployment
• Components use meta data instead of registration
• support side-by-side, multiple component versions
• command-line deployment(Xcopy) and uninstall(DEL)
3. support development languages
• provide rich base classes for developer tools and languages
4. support multiple languages
• define CTS that are used by all .NET languages
5. enable convergence of programming models
• Build languages and tools on a common framework. For example, ASP .NET,
VB .NET, and C# have access to the same base classes.

Overview of the CLR:

Base Class Library Support


Thread Support COM Marshaller

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Type Checker Exception Manager


Security Engine Debug Engine
IL to native Code Manager GC
Compilers
Class Loader

Q.: Explain VES (Virtual Execution System):

• The CLR provides a number of runtime support services using the VES. The VES is
responsible for implementing and enforcing the CTS. The VES is designed to run
managed code, that is, code that supports the CTS. The execution engine uses
Meta data information to understand the structure of the components.

The Specific components of the VES are:

• Class Loader(Load Managed Code)


• MSIL
• MSIL-to Native Code Conversion
• Verification of Type safety, according to CTS.
• Stack Walker(services based on stack heap)
• Memory Management and Garbage collection
• Profiling and Debugging
• Co-Instance Execution
• Unmanaged Code.

Q.: Explain Dot Net Assembly:

It is the standard for components developed by Microsoft. The assembly may or may
not contain exe file that is it can be .exe file or dynamic link library file (.dll). Main
component of assembly contains the definition of type’s versioning information for the
type metadata and manifest. The assembly can be used by single or multiple application.
There are 2 types assembly in dot net.
 Private
 Shared

1. Private assembly:- they are simple and used by single application & stored in the
application directory. This are used to deploy language specific resource and it
works in side by side execution. Because the application has a separate product id

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

for each language & installs satellite assembly in a language specific sub directory
for each language.

2. Shared assembly: - It is stored in global assembly cache (GAC) memory location


for common access. This is repository of assembly maintained by the dot net at
runtime. Each shared assembly has 4 parts including its face name, version, public
key and culture information.

Components of Assembly:

A static assembly consist of 4 elements:-


1. The assembly manifest, which contains assembly metadata.
2. Type metadata
3. Microsoft intermediate language(msil) code that implement the type.
4. A set of resources.

 Assembly manifest :-

Every assembly whether static or dynamic contain a collection of data that


describes how the element in assembly relates to each other. It contain its
assembly metadata such as assembly version requirement & security identity & all
metadata needed to define this scope of the assembly & resolve references to
resources & classes. It can be stored in either PE file(portable exe file) or .dll file
with Microsoft intermediate language(MSIL) code or in a standalone PE file that
contains only assembly manifest information.

The following illustration show the different ways to manifest can be stored.

File1.dll
manifest File2.dll Graphics.jpg Logo.bmp

manifest

The following table shows the information contain in the assembly manifest.

Information Description
Assembly name A text string specifying the assembly

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

name.
Version number A major & minor version number & a
revision & build number. The common
language runtime uses this no. To
nenforce version policy.
Culture Information on the culture or language
the assembly supports the informayion
should be use only to designate and
assembly as a satellite assembly
containing culture or language specific
information.
Strong name Information The public key from the publisher if the
assembly has been given a strong
name.

Q.: Explain Garbage collector

The garbage collector is a tool for memory management provided by dot net framework.
It runs in low priority thread and checks for those objects which are not referenced
dynamically allocated memory space.

 If it finds some data that is no longer needed it frees up memory & returned back
to the OS so that it can be used by other programs
 Garbage collector frees the programmer from keeping track of un-referenced
data.
 Garbage collector provides explicit memory management & manages memory
leaks.
 Garbage collector checks how objects are arranged in memory and identifies all
those object that can be used by the running programs.
 Garbage collector marks this object as live. If they have reference once all of these
live objects are known. Any other objects can be declared and the space can be
reuse for new objects
 Dot net reduces memory so that there ios no gap & free memory is always
available at the end of the heap.
 When a garbage collection start. It looks at a set of references called ‘GCroot’ . it
contains references to objects created by the program.

Q.: Explain JIT compiler

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

When compiling to managed code the compiler translates your source code into
Microsoft intermediate language (MSIL.), which a CPU independent set of instructions
that can be efficiently converted to native. MSIL includes instruction for loading, storing,
initializing & calling method on objects as well as instruction for arithmetic & logical
operation control flow, direct memory access, Exception handling & other operations.
Before code can be run, MSIL must be converted to a CPU specific code just-in-time (JIT)
compiler. Because the common language runtime supplies one or more JIT compilers for
each computer architecture it supports. The some set of MSIL can be JIT compiled run
on an supported architecture.

When a compiler produces MSIL, it also produces metadata describes the types in
your code including the definition of each type the signature of each types. Members,
the members that your code references & other data that the runtime uses at execution
time. The MSIL & metadata are contained in a portable exe file.

JIT compilation takes into account the fact that save code might never get called
during execution rather than using time & memory to convert all the MSIL in a PE file to
native code, it converts the MSIL as needed during execution & stores the resulting
native code so that it is accessible for subsequent calls the loader creates & attaches a
stab to each of a types method when the type is loaded on the initial call to the method,
the stab passes control to the JIT compiler which converts the MSIL for that method info
native code & modifies the stab to direct execution to the location of the native code.

Q.: Explain Features of C#

Although C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language. It has strong resemblance with Java,
it has numerous strong programming features that make it endearing to a number of
programmers worldwide.
Following is the list of few important features of C#:
 Boolean Conditions
 Automatic Garbage Collection
 Standard Library
 Assembly Versioning
 Properties and Events
 Delegates and Events Management
 Easy-to-use Generics
 Indexers

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

 Conditional Compilation
 Simple Multithreading
 LINQ and Lambda Expressions
 Integration with Windows

Q.: Explain About Namespace

Namespace are C# program element designed to help you organize your programs. They
also provide assistance in avoiding name classes between two set of code.
Implementing Namespace in your own code is a good habit because it is likely to save
you from problems later when you want to reuse some of your code. For example :- if
you create a class named console you would need to put it in your own namespace to
ensure that there wasn’t any confusion about when the system console class should be
used. Generally it would be a bad idea to create a class named console.

System Namespace in fundamental namespace for C# application. It contains all the


fundamental classes and base classes which are required in simple C# application. These
classes and sub classes defines references some classes provide some other feature like
data types conversion.

Q.: Explain Datatypes

The types of data that a variable contain is called Datatype. A Datatype is a classification
of things that share similar type of qualities or characteristics or behaviour .

C# strongly typed language so every variable and object must have a type.

These are two type of data type in C#.

i. Primitive types or predefined


Eg:-byte, short, int , float, double, long, char, bool, DateTime, string object etc.
ii. Non-primitive types or user defines
Eg:- class , struct, enum, interface, delegate, array.

The varibles in C#, are categorized into the following types:


 Value types
 Reference types
 Pointer types

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Value Type

Value type variables can be assigned a value directly. They are derived from the class
System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which
stores numbers, alphabets, and floating point numbers, respectively. When you declare
an int type, the system allocates memory to store the value.
The following table lists the available value types in C# 2010:

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method. The expression sizeof(type) yields the storage size of the object or
type in bytes.
For example if you type
Console.WriteLine(sizeof(int)),
you will get the output as 4, the bytes occupied by an integer.

Reference Type
The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference
types can refer to a memory location. If the data in the memory location is changed by
one of the variables, the other variable automatically reflects this change in value.
Example of built-in reference types are:
 object,
 dynamic, and
 string.

Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System
(CTS). Object is an alias for System. Object class. The object types can be assigned
values of any other types, value types, reference types, predefined or user-defined
types. However, before assigning values, it needs type conversion.

Q.: Explain Boxing and Unboxing


Boxing means implicitly converting a value type to the type object. When a value
type is boxed, an object instance is allocated and the value present in the value type is
copied into the new object. Unboxing refers to the converting of an object type to any
value type. We have to explicitly tell the compiler what value type we want to extract
from the object type.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Example:

int m=100;
object ob=m;// we have created a box named ob and thus initiated boxing action.
object ob= (object) m //Explicit way of boxing which is optional
int num= (int) ob;// Unboxing

Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time. Dynamic types are similar to object
types except that type checking for object type variables takes place at compile time,
whereas that for the dynamic type variables takes place at run time.
For Example
dynamic dy=200;

String Type
The String Type allows you to assign any string values to a variable. The string type is an
alias for the System.String class. It is derived from object type. The value for a string
type can be assigned using string literals in two forms: quoted and @quoted.
For example,
String str="String handling";

The user-defined reference types are:


 class,
 interface,
 delegate.

Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have
the same capabilities as the pointers in C or C++.
Pointers are supported to some extent by .NET. It considers the instructions as unsafe
and we have to include them under unsafe block.

For Example,
unsafe{
char *c; }

MANAGED,UNMANAGED AND UNSAFE:

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Managed code is simply code that runs under the CLR with its common types, error
handling, debugging, and memory management. Even managed code can be unsafe and
being unsafe is more than just pointer specific. For example, the following C# code is
managed but unsafe:

Unsafe
{
Console.WriteLine(“Datetime size in
bytes”,sizeof(DateTime));
Console.WriteLine(“Short size in bytes”,sizeof(short));
Console.WriteLine(“int size in bytes”,sizeof(int));
Console.WriteLine(“long size in bytes”,sizeof(long));
}

• The C# code used the sizeof keyword will only compile if placed in an unsafe block. At
present the DateTime structure is 8 bytes. in some future version of .NET this
structure could be 12 bytes. this would mean that all the code compiled with the
present version of .NET would be invalid.
• Unsafe does not refer to present tense behavior but is a warning. it enables the
developers to use good and safe coding practices.
• If we use the stack, to print the DateTime, such a structure is unsafe, because this
data is placed on the stack. If this value goes out of scope, the stack location being
pointed to could change; this would result in unpredictable behavior.
• It is possible to allocate data on the stack using C#’s stackalloc keyword. But it cannot
be used to create reference types. Using stackalloc is unsafe, because if buffer went
out of scope, the contents of the stack could be unknown and would lead to
unpredictable behavior.

Q.: Explain Type Conversion

When one type of is assigned to another type of variable an implicit type conversion will
take place automatically if

i. The two types are compatible.


ii. The destination type has a range that is greater than the source type.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

When this two condition are met a widening conversion takes place. For example the int
type is always large enough to hold all valid byte values and both int and byte are
compatible integer types so an implicit conversion can be applied. For widening con
versions the numeric keys including integer and floating point type are compatible with
each other.
 Casting Incompatible types
Although the implicit type conversion are helpful they will not fulfil all
programming needs because they apply only to widening conversions between
compatible types. For
All other cases you must employ a cast .a cast is an instruction to the compiler to
convert the outcome of an expression into a specified type. thus it request an
explicit type conversion.
A cast has this general form(target.type)expression
Here, target-type specifies the desired type to covert . he specified expression
too.for example given
doublex,y;

if you want type of the expression x/y to be int you can write int(x/y).

for example :-

using system;
classcastDemo
{
public static void Main(string []aegs)
{
double x, y;
byte b;
int I;
charch;
short s;
long l;
x=10.0;
y=3.0;
i=(int)(x/y);
Console.Writeline(“Integer outcome of x/y:”+i);
i=255;
b=(byte)I;
Console.Write(“b after assigning 255”+b+”no data lost”);

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

b=88;
ch=(char)b;
Console.Wrtieline(“ch after assigning 88:”+ch);
}
}

Q.: Explain Operators in C#

An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. C# has rich set of built-in operators and provides the following
type of operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#.

Operator Description
+ Adds two operands
- Subtracts second operand from the first
* Multiplies both operands
/ Divides numerator by de-numerator
% Modulus Operator and remainder of after an
integer division
++ Increment operator increases integer value by
one
-- Decrement operator decreases integer value by
one
Relational Operators
Following table shows all the relational operators supported by C#.

Operator Description
== Checks if the values of two operands are equal or not, if
yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

values are not equal then condition becomes true.


> Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the value
of right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or
equal to the value of right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is less than or equal to
the value of right operand, if yes then condition becomes
true.
Logical Operators
Following table shows all the logical operators supported by C#.

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

The Bitwise operators supported by C# are listed in the following table.

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

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

>> Binary Right Shift Operator. The left operands value is


moved right by the number of bits specified by the
right operand.
The truth tables for &, |, and ^ are as follows:

A B A&B A|B A^B


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assignment Operators
There are following assignment operators supported by C#:

Operator Description
= Simple assignment operator, Assigns values from right
side operands to left side operand
+= Add AND assignment operator, It adds right operand to
the left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to
left operand
*= Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to
left operand
/= Divide AND assignment operator, It divides left operand
with the right operand and assign the result to left
operand
%= Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left
operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
^= bitwise exclusive OR and assignment operator
|= bitwise inclusive OR and assignment operator
Other Operators
There are few other important operators including sizeof, typeof and ? : supported by
C#.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Operator Description
sizeof() Returns the size of a data type.
typeof() Returns the type of a class.
& Returns the address of an variable.
* Pointer to a variable.
?: Conditional Expression
Is Determines whether an object is of a
certain type.
As Cast without raising an exception if the
cast fails.

Q.: Explain For ---each loop


for each loop is a different kind of looping constructs in C# programming that does
not includes initialization termination and increment or decrement characteristics. It
uses collection to take value one by one and then processes them.
For each loop is a loop construct. It does not use an integer index. Instead it is
used on a collection and return each element in order. This is called enumeration.
It eliminate error caused by incorrect index handling.
We first use the keyword for each on a string array to loop through the
element in the array.
In the for each statement .you do not need to specify the loop bound minimum
or maximum .you do not need on “i” variable in for loops.
Syntax:-
Foreach(string name in array)
{
}
Where name is a string variable that takes value from collection as arr and then
process them in the body area.
=>example
Using system;
Class program
{
public void print(int [] arr)
{
foreach (int x in arr)
{
Console.Writeline(x);
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
Public static void Main (string [] args)
{
Program a=new program();
Int [] x={1,2,3,4,5};
a.print(x);
console.Readline();
}
}
significance of foreach loop:-
 It does not use an integer index
 It eliminates error caused by incorrect index handling.
 It is use for read only purpose and do not have to specify exit.

Q.: Passing Parameters to a Method


When method with parameters is called, you need to pass the parameters to the
method. There are three ways that parameters can be passed to a method:

1. value,
2. reference and
3. Output Parameters

Value Parameters:

This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.
Reference Parameters:

This method copies the reference to the memory location of an argument into the
formal parameter. This means that changes made to the parameter affect the argument.
Output Parameters:

This method, meaning the method with output parameters, helps in returning more
than one value.

Call by value :

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

This is a parameter declared with no modifier is passed by value ans is called a value
parameter when a method is invoked .the values of actual parameter are assigned to
the corresponding formal parameter . the value of the value parameter can be change
within the method . the value of the actual parameter that is passed by value to a
method is not changed by any changes mode to the corresponding formal parameter
within the body of the method refer to only copies of those variables when they are call
by value.

For eg:-

Using system;

Class Increment

{
//define a function incr
public static void Incr(int i)
{
i++;
console.Writeline(i);
}
Public static void Main(string [] args)
{
Int x=2;
Incr(x);//calling a function incr
Console.Writeline(x);
}
}
Call by reference:

We can force the value parameter to call by reference. To do this


we can use “ref” keyword .A parameter declared with the ref modifier is a reference
parameter

Eg:-void modify (ref int x)

Here x is declared as a reference parameter unlike a value , a reference parameter does


not create a new storage location .Instead it represent the some storage location as the
actual parameter used in the method invocation. when a formal parameter is declared

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

as ref the corresponding agreement in the method invocation must also be declared as
ref.

Eg:- void modify(ref int x)

{
X+=10; //value of m will be changed.
}
………..

Int m=5; //m is initialized

Modify (ref m);//call by reference

The use of ref int as the parameter type in the definition and use of ref keyword in the
method call to tell the compiler to call by reference rather than by value.

=>for eg:-

Using system;
Class Increment
{
//definition of function incr
Public static void Incr(ref int i)
{
i++;
Console.Writeline(i);
}
Public static void Main (string []args)
{
Int x=2;
Incr(ref x);//calling a fun incr
Console.Writeline(x);
}
}

Out parameter
They are used to pass result back to the calling method. This is achieved by declaring
the parameters with an out keyword. similar to a reference parameter does not create
a new storage location . Instead it because an alias to the parameter in the calling

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

method .when a formal parameter is declared as out , the corresponding actual


parameter in the calling method must also be declared as out.

=>for example:- void output(out int x)

{ x=100; }

Int m; //m is initialized

Output(out m);// value of m is set.

Here, the actual parameter m is not assigned any values before it is passed as output
parameter since the parameter x and m refer to be the same storage location m takes
the value that is assigned to x.

=>for eg:-

Using system;

Class output
{
//define num1 function
Public static void Num1(int x, int y, out int z)
{
Console.Writeline(x+” “+y);
Z=x*y;
Console.Writeline(z);
}
Public static void Main(string [] args)
{
Int i=2; int j=3; int k;
Num1(I,j,out k) //calling num1 function
Console.Writeline(k);
}
}

1.5.3 Parameter Arrays:

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

In C# we can define methods that can handle variable number of argument using what
are known as parameter arrays. Parameter arrays are declared using the keyword
params.

Eg:- void function1(Paramsint []]x)

{ }

Here, x has been declared as a parameter array. Note that parameter arrays must be
one-dimensional arrays. A parameter may be a part of a formal parameter list and in
such case it must be the last parameter .

The method function1 defined above can be invoked in two ways:-

i. Using int type array as a value parameter.


eg. Function1(a);

Here, a is an array of type int.

ii)Using zero or more int type arguments for the parameter array.

eg: function(10,20);

the second invocation creates on it int type array with two elements 10 and 20 and
passes the newly created array as the actual argument to the method.

for eg: using system;

class params

{
//defining function parray
static void parray(params int[] arr)
{
console.writeline("Array elements are:");
foreach(int i in arr)
console.writeline(" "+i);
console.writeline();
}
public static void main()
{

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

int[] x={11,22,13};
Parray(x); //calling parray function
Parray( ); //calling parray function
Parray(100,200); //calling parray function
}
}

1.5.4 Recursive Functions:

A function calling itself is known as recursive methods or functions. In order to faster


the performance and to increase the usage of stack memory efficiently, recursive
methods are used.

Example:

//program to print Fibonacci series (0,1,1,2,3,5,8,13...)

using System;

namespace myns{
class recurdemo{
static void PrintFibo(int a,int b,int n)//defining function with 4 params. n param to count
the number of elements in the series.
{
c=a+b; //adding first two parameters
if(c<n)
{
Console.Write(c+",");
//call printFibo fun again to print the series in the same manner
PrintFibo(b,c,n);//n should be reduced to n-1 as we printed an element
}
}
static void Main(){
int a,b,c,n;
a=0;
b=1;
Console.WriteLine("Enter the number of elements you want in series");
n=int.Parse(Console.ReadLine());
Console.Write(a+",");
Console.Write(b+",");
PrintFibo(a,b,n);

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
}}

Q.: Explain Access modifiers

Encapsulation is implemented by using access modifiers. An access modifier defines


the scope and visibility of a class member. C# supports the following access modifiers:
 Public
 Private
 Protected
 Internal
 Protected internal

Example 1
class Demo
{
private int age;

public int Age


{
set(value){age=value; }
get { return age; }
} }

Real-world Example of Encapsulation


we can operate television with a remote and there is no need to open the TV to change
the channel or to do any adjustment. Here everything is private except the remote, so
that anyone can access the remote to operate and change the things in the TV.

Public Access Modifier

Public access modifier allows a class to expose its member variables and member
functions to other functions and objects. Meaning any public member can be accessed
from outside the class.

Consider the following example:


using System;
class Rect {
//Instance members
public double length;

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public double width;

public double CalcArea()


{
return length * width;
}
public void Display()
{
Console.WriteLine(" "Area of Rect is:", CalcArea());
}
}//class Rect is terminated

class Demo
{
public static void Main(string[] args)
{
Rect r = new Rect();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Area of Rect is: 15.75

In the preceding example, the member variables length and width are declared public,
so they can be accessed from the function Main() using an instance of the Rectangle
class, named r.

The member function Display() and GetArea() can also access these variables directly
without using any instance of the class.

The member functions Display() is also declared public, so it can also be accessed from
Main() using an instance of the Rectangle class, named r.

Private Access Modifier

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Private access modifier allows a class to hide its member variables and member
functions from other functions and objects. Only functions of the same class can access
its private members. Even an instance of a class cannot access its private members.

Consider the following example:


using System;
class Rect {
//Instance members
private double length;
private double width;
public void GetData() //members' initialization through Mutator or Accessor methods
{
Console.WriteLine("Enter length and width");
length=double.Parse(Console.ReadLine());
width=double.Parse(Console.ReadLine());
}
public double CalcArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine(" "Area of Rect is:", CalcArea());
}
}// class Rect is terminated

class Demo
{
public static void Main(string[] args)

{
Rect r = new Rect();
r.GetData(); //calling mutator
r.Display(); //calling public display function and thus calling CalcArea()
Console.ReadLine();
}
}
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

When the above code is compiled and executed, it produces the following result:
Enter Length:
4.4
Enter Width:
3.3
Area of Rect is: 14.52

In the preceding example, the member variables length and width are declared private,
so they cannot be accessed from the function Main(). The member
functions GetData()and Display() can access these variables. Since the member
functions GetData() and Display() are declared public, they can be accessed
from Main() using an instance of the Rectangle class, named r.

Protected Access Modifier

Protected access modifier allows a child class to access the member variables and
member functions of its base class. This way it helps in implementing inheritance. The
example of the same will be explained in inheritance topic.

Internal Access Modifier

Internal access modifier allows a class to represent its member variables and member
functions to other functions and objects in the current assembly. It is similar to default
or friendly modifier of java. Java's friendly modifier members can be accessed from any
class or method defined within the package. Where as in C#, any member with internal
access modifier can be accessed from any class or method defined within the assembly
in which the member is defined.

For Example:
using System;
class Rect
{
//instance variables with friendly modifier
internal double length;
internal double width;

double CalcArea()
{
return length * width;
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public void Display()


{
Console.WriteLine("Area of Rect is:", CalcArea());
}
}//class Rectangle is terminated

class Demo
{
public static void Main(string[] args)
{
Rect r = new Rect();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Area of Rect: 15.75

In the preceding example, notice that the member function CalcArea() is not declared
with any access modifier. Then the default access modifier of a class member is private.

Protected Internal Access Modifier

The protected internal access modifier allows a class to hide its member variables and
member functions from other class objects and functions, except a child class within
the same application. Like of protected this modifier also will be implemented in
inheritance.

Q.: The Differences between Abstraction and Encapsulation

S.No Parameters Abstraction Encapsulation


1. Solution Level to the Encapsulation solves
Abstraction solves the
problem the problem in the
problem at the design level.
implementation level.
2. Information/Data hiding Abstraction hides Encapsulation means
unwanted data hiding the code and
and provides relevant data. data into a single unit to

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

protect the data from


the outside world.
3. Focus of concern Encapsulation means
Abstraction lets you focus hiding the internal
on what the object does details or mechanics of
instead of how it does it how an object does
something.
4. Layout Encapsulation- Inner
layout, used in terms of
Abstraction: Outer layout,
implementation.
used in terms of design.
For example: the
For example:
internal details of a
An external of a Mobile
Mobile Phone, how the
Phone, like it has a display
keypad button and
screen and keypad buttons
display screen are
to dial a number.
connected with each
other using circuits.

Q.: Explain Constructors in C#


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.
Attributes in C#, which are private/protected/internal/protected internal/public, are
initialized through the following ways.
 Mutator (Accessor methods)
 Properties (get/set)
 Constructors
Thus, through constructors, properties of the class is initialized.
Following example explains the concept of constructor:
using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
int w=h=5; //members are initialized here.
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public void display()


{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: 5,5

1.7.9.1 Types of Constructors:


 Null Constructor
 Default Constructor
 Static initialization of a Constructor
 parameterized Constructor
 dynamic initialization of a Constructor
 static Constructor
 overloaded Constructor

Null Constructor:
A constructor that initiates private properties of the class with null values by accepting
null parameter is termed as Null Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
//members are initialized with null values here.
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: ,

Default Constructor:
A constructor that initiates private properties of the class with their default values by
accepting null parameter is termed as Default Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
w=h=0; //members are initialized to their default values here.
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: 0,0

Static initialization of a Constructor:


A constructor that initiates private properties of the class with static values by
accepting null parameter is termed as Static initialization of a Constructor.
using System;
namespace consns
{
class Box
{
int w,h;

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public Box()
{
w=5;
h=7;
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: 5 , 7

Parameterized Constructor:
A constructor that initiates private properties of the class with dynamic values by
accepting parameters for the same is termed as Parameterized Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box(int w1,int h1)
{
w=w1; //w will be initialized to w1
h=h1; //h will be initialized to h1
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box(12,23);//construct an instance of Box b---process of
instantiation
b.display();
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

} }
When you run this program, you will get the following output:
The width and height of the Box is: 12 , 23

Dynamic initialization of a Constructor:


A constructor that initiates private properties of the class with dynamic values by
accepting parameters for the same is termed as Dynamic initialization of a
Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box(int w1,int h1)
{
w=w1; //w will be initialized to w1
h=h1; //h will be initialized to h1
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b;
int x,y; //local variables declaration
Console.WriteLine("Enter two numbers");
x=int.Parse(Console.ReadLine()); //converted input String to integer
y=int.Parse(Console.ReadLine()); //converted input String to integer
b=new Box(x,y);//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
Enter two numbers:
11
17
The width and height of the Box is: 11 , 17

Static constructor:-

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

 Static constructor is called before any object is created it is used to assign initial
value to static data members .
 static constructor cannot have any parameter and it can have only static member
inside.
 static variables are shared by all the object of a class & there is only one copy into
memory & we can change the value of static variable
 constant variables are also shared by all objects, but no object can change its
value.
->For eg:
using System;
class Area
{
int x;
static int i;
constant int z=100;
static Area( )
{
i=00;
}
void print( )
{
console writeline(i);
}
public static void Main(string[]args)
{
Area a=new Area( );
a.print( );
}
}

When you run this program, you will get the following output:
0

Overloaded Constructor/Constructor Overloading:

To create an overloaded constructor, all we have to do is to provide several different


constructor definitions with different parameter list .the difference may be in either the
number or type of arguments, that is each parameter list should be unique .
Here is an example of creating on overloaded constructor.
=>

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

using System;
class Area
{
int a,d;
float c;
Area(int i,int b)
{
a=i;
d=b;
}
void rectangle( )
{ int Rect=a*b;
console.writeline(Rect);
}
Area(int s)
{
a=s;
}
void Square( )
{
int squ=s*s;
console.writeline(squ);
}
Area(float rad)
{
c=rad;
}
void circle()
{
float circ=3.14*c*c;
Console.WriteLine(circ);
}
public static void Main(string[ ] agrs )
{
Area A1=new Area(2;5);
A1.Rectangle( );
Area A2= new Area(5);
A2.Square( );
Area A3=new Area(3.5f);
A.circle( );

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
}

1.7.10 Destructor:

A destructor is a special member function of a class that is executed whenever an


object of its class goes out of scope. A destructor has exactly the same name as that of
the class with a prefixed tilde (~) and it can neither return a value nor can it take any
parameters.
If Constructor is for memory allocation then destructor is for memory de-allocation.
Destructor can be very useful for releasing memory resources before exiting the
program. Destructors cannot be inherited or overloaded.

using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
Console.WriteLine("Object is Created");
}
~Box()
{
Console.WriteLine("Object is Deleted");

}
public static void Main(string []arg){
Box b1=new Box();//calling constructor
Console.WriteLine("In Block1");
{
Box b2=new Box();//calling constructor
} //calling destructor
Console.WriteLine("In Block2");
{
Box b3=new Box();//calling constructor
} //calling destructor
} //calling destructor
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
When you run this program, you will get the following output:
Object is created
In Block1
Object is created
Object is deleted
In Block2
Object is created
Object is deleted
Object is deleted

1.7.11 Types of members of a class:

 Constant member
 Static member
 Read-only member
Constant member:

C# permits declaration of data fields of a class as constants this can be done using the
modifier constant.

ex: public constant int size=100;

The member size is assigned the value 100 at compile time and cannot be changed later.
Although constant members are implicitly static, we cannot declare them so explicitly
using static for eg. the statement public static constant int size=100; is wrong
and will produce compile time error;
ex:-
using System;
class Area
{const int z=100;
Area(int z)
{
z=x;
Console.WriteLine(z);
}
public static void Main(string[ ] args)
{
Area a=new Area(5);

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
}
Read-only members:

This is modifier is designed to set the value of the member using a constructor
method ,but cannot be modified later. The read-only members may be declared as
either static field are declared as instance fields, they can take different value with
different object.
=> ex:
using System;
class Area
{
readonly int y;
Area(int x)
{
y=x;
}
public static void Main(string[ ] agrs)
{
Area a= new Area(5);
Area a1= new Area(6);
Area a2= new Area(7);
}
}

Static members:

Assume that we want to define a number that is common to all the object and accessed
without a particular object that is the member belong to the class as a whole rather
than the object created from the class such members can be defined as follows:
static int x;
static int max(int a,int b);
The member that are declared static as shown above are called static members.
=>for ex:-
using System;
class Area
{
int x;
static int i;
static Area( )

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

{
i=100;
}
void print( )
{Console.WriteLine(i);
}
public static void Main(string[ ] agrs)
{
Area a=new Area( );
a.print( );
}
}

1.7.12 Inheritance

When a class includes a property of another class it is known as inheritance. Inheritance


is a process of object reusability. Creation of the new class by extending the features of
an existing class is known as Inheritance.

Rules of Inheritance:

a) The child class should inherit all the features of the parent class.
b) It should have its own unique features too.
c) The rule of substitutability should be followed. (Meaning, through sub/child class
object one can access all the features of parent class and child class as well.)

1.7.12.1 Consider the following simple example:


public class ParentClass
{
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass : ParentClass
{
public void PrintChild()
{
print();//calling parent class print function

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Console.WriteLine("I'm a Child Class.");


}

public static void Main()


{
ChildClass child = new ChildClass();
child.PrintChild();
} }

Output
I'm a Parent Class.
I'm a Child Class.

1.7.12.2 Another Example of inheritance


//with constructor overriding characteristics
//Add another public variable called horse power in car class
public Class Car
{
protected string color;
protected int _speed;
/*Now add the doors property
In the car class add a private property for doors*/
protected _numberOfDoors as Integer = 5;
protected string HorsePower;
public Car(){
color="red";
_speed=20;
HorsePower=240;
}
public void accelerate(int a){
_speed+=a;}
public bool IsMoving(){
if _speed = 0
Return false;
else
Return true;
}
}
public Class SportsCar : Car
{

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public int Weight;


public SportsCar(){
//if super class constructor is not invoked by calling base();//calling super class
constructor then sub class constructor overrides the super class constructor
color="white";
_speed=40;
HorsePower=250;
weight=1085;}
public double GetPowerToWeightRatio(){
Return (HorsePower/Weight;
}
public displayCarDetails(SportsCar s){
Console.WriteLine("Color:" +s.Color);
Console.WriteLine("Speed:" + s.Speed);
Console.WriteLine("Number of doors:" + s.NumberOfDoors);
}
public static void Main(){
SportsCar mycar = New SportsCar();//calling sub class constructor
mycar.Accelerate(5);
Console.WriteLine("car's horsepower is"+mycar.HorsePower);
Console.WriteLine("car's weight is"+mycar.Weight);
Console.WriteLine("Mycar is "+ mycar.color +" in color. "+);
Console.WriteLine("car's speed is"+mycar.Speed);
Console.WriteLine("The car is Moving:"+mycar.isMoving());
displayCarDetails(mycar);//calling display car function of sports car object
Console.ReadLine();
}//main function is terminated
}//class is terminated

1.7.12.3 Types of Inheritance:

We can broadly classify the inheritance as


 Classical and
 Containment Inheritance.

1.7.12.3.1 Classical Inheritance:


The idea of classical inheritance implements the IS-A relationship.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

members of an existing class. This existing class is called the base class, and the new
class is referred to as the derived class.
For example, Whale IS-A mammal; Blue-whale IS-A Whale and hence Blue-whale IS-A
mammal and so on.
Mammal

Whale is Mammal

Whale

Blue Whale is a Whale

Blue Whale is
Mammal Blue Whale

Classical Inheritance is further divided into


 Single Inheritance
 Multi-level Inheritance
 Hierarchical
 Multiple Inheritance

Classical
Inheritance

Single Multi-level Hierarchical Multiple


Inheritance Inheritance Inheritance Inheritance

1.7.12.3.1.1 Single Inheritance:

Example 1.7.12.1 is applicable to this type of inheritance.

1.7.12.3.1.2 Multi-level Inheritance:

When one class is derived from another Child class then this type of inheritance is called
multilevel inheritance. The diagram of the same will mimic like the one we have used to
explain classical inheritance. Blue whale---Whale---Mammal example.
Let us program the same example.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

using System;
namespace inhns
{
class Mammal
{
protected void About(){
Console.WriteLine("The mammals include the largest animals on the planet, as
well as some of the most intelligent, some primates and some cetaceans");
}
}//mammal class is terminated
class Whale : Mammal
{
protected void Types()
{
About(); //calling base class about function to display about
mammals
Console.WriteLine("Whale is one of the largest mammals. There are
about 86 species of whales.");
}
}//whale class is terminated

class BlueWhale : Whale


{
protected void Features()
{
Types();//calling base class about function to display about mammals
Console.WriteLine("Blue Whales are the largest animals ever to live on the
earth");
}
}
class MultilevelInhDemo
{
public static void Main(){
BlueWhale bw=new BlueWhale(); //instantiation of the least class in hierarchy.
bw.Features(); //through the object, call all the functions of super class indirectly.
/* Directly it can be invoked through the object of BlueWhale. Instructions such as
bw.Types(); bw.About(); are also legal.*/
}//main function is terminated.
} //multilevelinhdemo class is terminated

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}//namespace is terminated

1.7.12.3.1.3Hierarchical Inheritance:

This type of Inheritance is to denote the concept of inheritance by specialization. For


example B.Com is the base class then the specialization fields such as Banking&
Insurance, Financial Market and Accounts & Finance are the courses which has basic
B.Com features plus the special features of the concerned courses.

B.Com

B.Com(B&I) B.Com(A&F) B.Com(FM)

Diagram: to show the Hierarchical Inheritance

In the above diagram, even though B&I, A&F, FM courses are sibling courses, derived
from parent class B.Com, they can't share their properties and behaviours amongst
them. But they can inherit the features from its parent class of course as per the rule.

Consider the following Example:


using System;
namespace hierinhdemo
{
class BCOM{
public void features(){
Console.WriteLine("This course is the under-graduation course of
commerce domain");
}
}

class BBI: BCOM {


public void about(){
Console.WriteLine("This course is the under-graduation course of
commerce domain with the specialization in banking and insurance");
}
}
class BFM: BCOM{
public void about(){

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Console.WriteLine("This course is the under-graduation course of


commerce domain with the specialization in financial markets");
}
}
class BAF : BCOM{
public void about(){
Console.WriteLine("This course is the under-graduation course of
commerce domain with the specialization in accounts and finance");
}
}

class HierInhDemo
{
public static void Main(){
BAF f=new BAF();
BFM m=new BFM();
BBI i=new BBI();
f.about();//will display about BAF course
m.about();//will display about BFM
i.about();//will display about BBI
//to display the features of BCOM course, any of the three objects can be
used.
i.features();
}
}
}

When you compile and execute the above program, the output will be
This course is the under-graduation course of commerce domain with the specialization
in accounts and finance
This course is the under-graduation course of commerce domain with the specialization
in financial markets
This course is the under-graduation course of commerce domain with the specialization
in banking and insurance
This course is the under-graduation course of commerce domain

1.7.12. 3.1.4 Multiple inheritance

Multiple inheritance in c# is not direct as like of CPP. It is implemented indirectly


through interfaces as like of Java.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Interface:

An interface is named collection of semantically similar abstract members or


functions .A class or structure may follow a behaviour that is prescribed by an interface.
The keyword interface is used to create an interface. If while defining members inside
an interface, there is number used to specify the access modifier as they are public by
default.
=>Syntax:-
interface interface1
{
}
interface interface2
{
}
public class subclass: interface1,interface2
{
}
Subclass is derived from interface1,interface2 like this we can derive a class from one or
more interface by just seperating interface names with comma(,).
Interface in C# provide a way to achive runtime polymorphism. Using interfaces we can
invokede function from different classes through the same interfaces reference whereas
using virtual functions we can invoke functions from different classes in the same
inheritance hierarchy through the same reference
=>example:-
using System;
namespace consoleApplication
{
interface interfaceDemo
{
void checkNum(int i);
}
class Demo1:Interface Demo
{
public void chekNum(int i)
{
}
public static void main(string[ ] args)
{
InterfaceDemo obj= new Demo();
obj.checkNum(8);

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
}
}

1.7.12.3.2 Containment Inheritance:

Unlike of Classical Inheritance, containment inheritance exhibits has-a relationship. A


class may contain objects of other classes and a class may have nested class. Example
like a room class has window object, door object etc.
Room

has-a has-a

Window
Door

Diagram: Containment Inheritance representation

Demo implementation of the above depicted scenario:

class Window
{
int h,w;
public Window(int h,int w){
//when the parameter name and instance member's name is same, c# allows us to
use this keyword to differentiate the instance members and parameters.
this.h=h;
this.w=w;
}
public void getSize(){
Console.WriteLine("Dimension is:"+ h+" ," +w);
}
}
class Door
{
int n;

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public Door(int n){


this.n=n;
}
public void getDoor(){
Console.WriteLine("Number of Door is:"+ n);
}
}

class Room{
public Window w;
public Door d;
public Room(){
w=new Window(300,200); //instantiated window object with the dimension
300X200
d=new Door(2); //instantiated Door object with number of doors in a room
}

}
class Demo{
public static void Main(){
Room myroom=new Room();
myroom.w.getSize();
myroom.d.getDoor();
}
}
When you compile and execute, the output will be:
Dimension is: 300,200
Number of Door is: 2

1.7.13
Polymorphism

Polymorphism means one name, many forms. One function behaves in different forms.
In other words, "Many forms of a single object is called Polymorphism."

Real-world Example of Polymorphism


Example 1
A person behaves the son in a house at the same time that the person behaves an
employee in an office. Here the person object's attitude is different in different
situations.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Example 2
Your mobile phone, one name but many forms:
 As phone
 As camera
 As mp3 player
 As radio

1.7.13.1 Types of Polymorphism

Polymorphism can be
 static or
 dynamic.
In static polymorphism, the response to a function is determined at the compile time.
So it is otherwise termed as Compile-time polymorphism. As the function definition
statements are bound with their calling instructions at compile-time statically, it may
be termed as Early/Static binding.

In dynamic polymorphism, it is decided at run-time. So it is otherwise termed as Run-


time polymorphism. As the function definition statements are bound with their calling
instructions at run-time dynamically, it may be termed as Late/Dynamic binding.

1.7.13.1.1 Static Polymorphism

The mechanism of linking a function with an object during compile time is called early
binding. It is also called static binding. C# provides two techniques to implement static
polymorphism. They are:
 Function overloading
 Operator overloading

Method/Function overloading:

In c# two or more method within the same class can share the same name as long as
their parameter declaration is different. Meaning we can have multiple definitions for
the same function name in the same scope. The definition of the function must differ
from each other by the types and/or the number of arguments in the argument list.
You cannot overload function declarations that differ only by return type.

 When this is the case the method are said to be overloaded and the process is
referred to as method overloading.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

 Method overloading is one of the ways that c# implements polymorphism.


 In general to overload a method, simply declare different versions of it.the
compiler take care of the rest.
 One important restriction the type and /or number of the parameters of each
overloaded method must differ.
 It is not sufficient for two methods to differ only in their return type. They must
differ in the type or number of their parameters.
 Return types do not provide sufficient information in all cases for c# to decide
which method to use.
 Overload method may differ in their return type.

For example:-
using System;
class Overload
{
public void ovlDemo()
{
Console.Writeline(“No Parameters”);
}
public void ovlDemo(int a)
{
Console.Writeline(“one Parameter:”+a);
}
public void ovlDemo(int a, int b)
{
Console.Writeline(“two Parameters:”+(a+b));
}
}
class OverloadDemo
{
public static void Main(string []args)
{
Overload ob=new overload();
Ob.ovlDemo();
Ob.ovlDemo(2);
Ob.ovlDemo(4,6);
}
}
When the above code is compiled and executed, it produces the following result:
No Parameters

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

One Parameter: 2
two Parameters: 10

Operator Overloading:

Static polymorphism is also implemented through operator overloading. Operator overloading is


the concept of making the operator to accept two objects or reference type variables as its
operands rather value type operands. Thus, we can overload the operators.
In operator overloading concept, both Unary and Binary operator can be overloaded. As we all
know, unary operator needs an operand, in unary operator overloading we have to provide an
object of the class to process or to act as an operand.
In binary operator overloading we have to provide two objects of the class to process or to act as
the operands.
Unary Operator Overloading Concept:
Consider the following example to illustrate the unary operator overloading concept.
//negation operator overloading example
class Space
{
int a;
double b;
Space(int a,double b){

this.a=a;
this.b=b;
}
public void operator -(){//overloading negation operator
a=-a;
b=-b;
}
public void display(){
Console.WriteLine("A is:"+a);
Console.WriteLine("B is:"+b);
}
}
class UnaryOpDemo{
public static void Main(string arg[]){
Space s=new Space(6,-7.8);
Console.WriteLine("B4 Negation");
s.display();
-s; //s.-() is also an accepted instruction

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

Console.WriteLine("After Negation");
s.display();
}
}
When you compile the above given program, the output will be
B4 Negation
A is: 6
B is: -7.8
After Negation
A is: -6
B is: 7.8

1.7.13.1.2 Dynamic Polymorphism

C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class
inherits from it. Abstract classes contain abstract methods, which are implemented by
the derived class. The derived classes have more specialized functionality.

Here are the rules about abstract classes:


 You cannot create an instance of an abstract class
 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes cannot be
declared sealed.

When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual functions. The virtual functions could be
implemented differently in different inherited class and the call to these functions will
be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.

The following program demonstrates an abstract class and virtual functions.

using System;
namespace PolymorphismApplication
{
abstract class Shape
{

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public abstract int area();


}
class Rectangle: Shape
{
private int l,w;
public Rectangle(int a,int b)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Area of Rectangle is :");
return (l*w);
}
}
class Square: Shape
{
private int side;
public Square(int a){
side=a;}
public override int area(){
Console.WriteLine("Area of Square is:");
return (s*s); }
}
class AbstractDemo
{
public static void Main(string[] args)
{
Shape s; //only object creation---not instantiation
s= new Rectangle(10, 7); //instantiated using Rectangle class
Console.WriteLine("Area:",s.area());//Through s we call area method of rectangle
s= new Square(5); //instantiated using Square class
Console.WriteLine("Area:",s.area()); //Through s we call area method of square
Console.ReadKey();
}//main function terminated
} //class is terminated
}//namespace is terminated
When the above code is compiled and executed, it produces the following result:
Area: Area of a Rectangle:

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

70
Area: Area of a Square:
25

1.7.14 Method Overriding in C#:

Method overriding is one of the types of inheritance and it is often identified as one of
the problems with inheritance. When super class and sub class have the same method
name with same signature, then sub class method overrides super class method upon
invocation through sub class object. Limiting the super class method in this passion is
otherwise termed as "Inheritance by limitation".
Object oriented languages such as C++ and Java supports this type of inheritance by
default. Meaning, they allow the sub classes to override their super classes by
redefining the methods of their parent classes.
But C# doesn't support this feature by default. The programmer can turn this feature
on by using the keywords
 virtual---override key pair and
 new

If they try those overriding, those instructions will be caught by C# compiler. So to try
out the method overriding, use the key pair virtual and override.
virtual---override keywords:
For example,
class ParentClass
{

public void display(){


Console.WriteLine(" I will be displayed");
}
}
class ChildClass: ParentClass
{
public void display(){ //this line will be caught by c# compiler. it is an error
//use keywords virtual--- override or new to do the same.
}
Let us modify the same example by adding virtual---override keywords.
using System;
namespace overridingns
{
class ParentClass

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

public virtual void display(){


Console.WriteLine(" I will not be displayed");
}
}
class ChildClass: ParentClass
{
public override void display(){
/* sub class should override display() when super class added with a keyword virtual for
the same function. Compiler will catch this line for error otherwise- If the subclass fails
to override/redefine the virtual function, c# compiler will throw an error. */
Console.WriteLine(" I will be displayed");
}
}
class OverridingDemo
{
public static void Main(){
ChildClass c=new ChildClass();
c.display(); // it will invoke the sub class display().
}
}

}
If you compile the program the output will be
I will be displayed

If you want to experience the output of the parent class display(), then modify the
above program as given below.

using System;
namespace overridingns
{
class ParentClass
{

public virtual void display(){


Console.WriteLine(" I may be displayed");
}
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

class ChildClass: ParentClass


{
public override void display(){
/* sub class should override display() when super class added with a keyword virtual for
the same function. Compiler will catch this line for error otherwise- If the subclass fails
to override/redefine the virtual function, c# compiler will throw an error. */
base.display(); //calling immediate super class display() using base keyword
Console.WriteLine(" I will be displayed");
}
}
class OverridingDemo
{
public static void Main(){
ChildClass c=new ChildClass();
c.display(); // it will invoke the sub class display().
}
}

}
If you compile the program the output will be
I may be displayed
I will be displayed

New Keyword:
It is obvious that override keyword should be used only with virtual keyword. In case if
the parent class doesn't have any method with virtual keyword but if the sub class
wants to override the super class method, then the key pair will not work. In this
scenario, the new keyword will help us handy. Thus it helps method hiding feature in
C#. Meaning super class method is hidden by sub class using new keyword.
To implement the new keyword we modify the above program as given below.

using System;
namespace overridingns
{
class ParentClass
{

public void display(){


Console.WriteLine(" I may be displayed");

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
}
class ChildClass: ParentClass
{
public new void display(){
/* sub class may hide display() of super class */
Console.WriteLine(" I will be displayed");
}
}
class OverridingDemo
{
public static void Main(){
ChildClass c=new ChildClass();
c.display(); // it will invoke the sub class display().
}
}

}
If you compile the program the output will be
I may be displayed
I will be displayed

1.7.15 Sealed Keyword:

Sealed keyword in c# works like final keyword of java. This keyword can be used with
function and class. If it is used with function then its subclasses cannot override its
parent classes’ methods even with new and override keywords. If it is used with classes
then they cannot be overridden.

Example of Sealed Keyword with method (function)


If we use Sealed Keyword with method then that method want to be accessible in its
derived class.
Example
Class sealed demo
{
Public virtual void checkNum(int i)
{
Int result=i*I;
}

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054


T.Y.BSc(I.T) SEM-V Gurunanak College Advanced Web Programming UNIT - I

}
Class Myderived:SealedDemo
{
Public sealed override void checknum(int x)
{
Int y = x*x*x;
}
Public static void main(string[] args)
{
MyDerived A=newmyDerived();
A.checkNum(i);
}
}

Example of Sealed Keyword with class:-If we make a class as Sealed class then that class
cannot be inherited by any other class.

Example
Class sealed:-
Sealed class sealDemo
{
Int I;
}
// class My class; sealDemo
{
Public static void main(string[]a)
{
}
} error base class cannot inherit derived class since base is sealed.

Compiled by. Prof. Mohd. Shahid(profshahid18@gmail.com) Mob. 7977-079-345 / 9821-77-1054

You might also like