0% found this document useful (0 votes)
146 views303 pages

C# Unit 1

The document provides an introduction to the .NET framework and its architecture. Some key points: 1) .NET framework provides a development environment for building applications using languages like C#, VB, and C++. 2) Visual Studio is used to develop applications like Windows and web apps that utilize .NET features and services. 3) The .NET architecture includes managed languages, the common language runtime (CLR), and common type system (CTS) to provide interoperability between languages.

Uploaded by

Sheraz Jabeen N
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)
146 views303 pages

C# Unit 1

The document provides an introduction to the .NET framework and its architecture. Some key points: 1) .NET framework provides a development environment for building applications using languages like C#, VB, and C++. 2) Visual Studio is used to develop applications like Windows and web apps that utilize .NET features and services. 3) The .NET architecture includes managed languages, the common language runtime (CLR), and common type system (CTS) to provide interoperability between languages.

Uploaded by

Sheraz Jabeen N
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
You are on page 1/ 303

C# and .

NET Framework - Introduction

Syllabus : .NET Architecture.

Section No. Topic Name Page


No.

1.1 Introduction to .NET Framework and its Architecture 1-2

1.2 The C# Language 1 - 10

1.3 OOP Concept 1 - 13

Two Marks Questions with Answers 1 - 19

Long Answered Questions 1 - 22

1-1 C# and .NET Programming


.NET Framework

1.1 Introduction to .NET Framework and its Architecture

Concept

1. It is widely used software development environment.


Explanation

2. Microsoft provided .NET framework which is a single platform for application


development using different programming languages that includes visual basic, visual C#
and visual C++.
3. Microsoft introduced development and execution software called visual studio which is to
be used for utilizing the features and services offered by .NET framework.
4. Visual studio is a tool that helps the application developer to develop wide range of
application softwares ranging from simple to complex. Visual studio provides
environment that enables to develop the applications such as console application,
windows form applications, WPF [Windows Presentation Foundation] applications, web
applications and web services.
5. Advantages of .NET framework
i) .NET framework provides environment to develop, execute, debug and test
applications using different programming languages that are .NET compliant.
ii) .NET provides consistent programming model based on object oriented technology
across different languages.
iii) Applications with wide range of tasks can be developed using .NET environment
common language runtime component in .NET environment handles the garbage
collection tasks by looking after the unused resources. That involves database and file
manipulations as well.
iv) In .NET environment resources like files, memory, database connections, media are
managed automatically and developer is relieved from the burden of freeing of unused
resources.
v) In .NET framework applications deployment is done in the form of assemblies hence
there is no need of registry entries to store information about components and
applications. In .NET framework, versioning problem while deployment is out of
question because .NET assemblies store information about different versions of
components used by an application that makes deployment very easy in .NET
framework.

1-2 C# and .NET Programming


.NET Framework

vi) .NET framework supports unique feature of language interoperability that enables a
piece of code written in one language to be used in another component written in
another language. Language interoperability feature improves efficiency of
development process thereby facilitating reusability of code.
6. .NET Framework Architecture
i) .NET is tiered, modular and hierarchal. Each tier of the .NET Framework is a layer of
abstraction.
ii) .NET languages are the top tier and the most abstracted level. The common language
runtime is the bottom tier and it is the least abstracted and closest to the native
environment. The common language runtime works closely with the operating
environment to manage .NET applications.
iii) The .NET Framework is partitioned into modules. Each module has its own distinct
responsibility. As the higher tiers request services only from the lower tiers, .NET is
hierarchal.
iv) The architectural layout of the .NET Framework is illustrated in Fig. 1.1.1.

Fig. 1.1.1 An overview of the .NET architecture

1-3 C# and .NET Programming


.NET Framework

v) .NET Framework is a managed environment. The common language runtime monitors


the execution of .NET applications and provides essential services. It manages
memory, handles exceptions, ensures that applications work properly.
vi) Language interoperability is one goal of .NET. .NET languages share a common
runtime (the common language runtime, a common class library), the Framework
Class Library (FCL), a common component model and common types.
vii) Common Language Runtime (CLR)
.Net Framework provides runtime environment called Common Language
Runtime (CLR).It provides an environment to run all the .Net Programs. The code
which runs under the CLR is called as Managed Code. Programmers need not to
worry on managing the memory if the programs are running under the CLR as it
provides memory management and thread management.
Programmatically, when the program needs memory, CLR allocates the memory for
scope and de-allocates the memory if the scope is completed.
Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program
to Microsoft Intermediate Language (MSIL) intern this will be converted to Native
Code by CLR as shown in below Fig. 1.1.2.

Fig. 1.1.2 Working of JIT

Types of JIT compilers :


JIT Compiler (Just In Time) compiler is a part of CLR (Common Language Runtime). It is
responsible for converting MSIL (binary format) to native code. It does this just before
execution. If any earlier compiled code already which already exists, if needed, is used here.

1-4 C# and .NET Programming


.NET Framework

There are three types of JIT compilers,


Pre-JIT: Also known as NGEN.exe (Native Generator), given by Microsoft, which in
one shot compiles complete MSIL code into native format (even before execution), so
that even the first-time execution of code is unaffected in terms of performance. In
this, the compiled output is saved in GAC (Global Assembly Cash).
Econo-JIT: Econo-Jit compiles only those methods which are called at run-time and
these methods are removed when they are not required. It is specially used in PDA’s;
here Econo-JIT does not do caching.
Normal-JIT: It compiles methods which are called at run-time. These methods are
called first time they are compiled and the results are stored in cache memory.
viii) Managed Languages and Common Language Specification (CLS)
.NET supports managed and unmanaged programming languages. Applications
created from managed languages, such as C# and VB.NET, execute under the
management of a common runtime, called the Common Language Runtime (CLR).
CLS makes a language to be .Net compliant. Microsoft has defined some
specifications that each .Net language has to follow. For e.g. no pointer, no multiple
inheritances etc. Common Language Specification (CLS) is a set of specifications or
guidelines defining a .NET language. Shared specifications promote language
interoperability. For example, CLS defines the common types of managed languages,
which is a subset of the Common Type System (CTS). This removes the issue of
marshaling, a major impediment when working between two languages.
There are several differences between a compiled managed application and an
unmanaged program.
1. MSIL :
a) Managed applications compile to Microsoft Intermediate Language (MSIL) (which is
intermediate language - IL) and metadata. MSIL is a low-level language that all
managed languages compile to instead of native binary.
b) When .NET code is compiled then it is not directly converted to native/binary code; it
is first converted into intermediate code known as MSIL code which is then
interpreted by the CLR. MSIL is independent of hardware and the operating system.

1-5 C# and .NET Programming


.NET Framework

Fig. 1.1.3 Portable executable

c) The compiled output of any MS.NET language (VB.NET, ASP.NET or C#) source
code is PE (Portable Executable either in .exe file or .dll files) and it comprises of
MSIL (Microsoft Intermediate Language) instructions and metadata in binary format.
d) Using just-in-time compilation, at code execution, MSIL is converted into binary
optimized both to the environment and the hardware. Since all managed languages
ultimately become MSIL, there is a high degree of language interoperability in .NET.
Cross language relationships are possible since MSIL is the same for all .Net
languages.

Fig. 1.1.4 Process of compilation

2. Metadata is data that describes data. In a managed application, also called an


assembly, metadata defines the types used and employed by the program. Managed
application’s, Interface Definition Language (IDL) files and type libraries together called
as the metadata. Metadata and the related manifest describe the overall assembly and the
specific types of an assembly.
3. Managed applications have limited exposure to the unmanaged environment. This
might be frustrating to many programmers, particularly experienced C gurus. However,
.NET has considerable flexibility. For those determined to use unmanaged code, there are
interoperability services.
4. In .NET, a managed application is called an assembly. An assembly adheres to the
traditional Portable Executable (PE) format but contains additional headers and sections

1-6 C# and .NET Programming


.NET Framework

specific to .NET. MSIL and metadata are the most important new additions to the .NET
PE. When the .NET Framework is installed, a new program loader recognizes and
interprets the .NET PE format. In future Windows operating systems, the first being .NET
Server, the .NET loader is automatically provided.
ix) Common Type System
The Common Type System (CTS) is a catalog of .NET types. System.Int32,
System.Decimal, System.Boolean and others. Developers are not required to use these
types directly. These types are the underlying objects of the specific data types
provided in each managed language. The following is the code for declaring an
integer in C# and Visual Basic .NET. Either syntax maps to a System.Int32 object.
Preferably, one should use the syntax of the language and not the underlying object
type, leaving .NET the flexibility to select the most appropriate type and size for the
operating environment.
The common type system is a pyramid with System.Object at the top most. .NET
types are separated into value and reference types. Value types, which are mainly
primitive types, inherit from System.ValueType and then System.Object. Reference
types is anything which is not a value type and are derived from System.Object, either
directly or indirectly. Value types are short-term objects and are allocated on the
stack. Reference types are essentially pointers and allocated on the managed heap.
The lifetime of reference types is controlled by the Garbage Collector. Value types
can be converted to reference types, and vice versa, through processes called boxing
and unboxing, respectively.

Fig. 1.1.5 CTS

CTS helps with type safeness, enhances language interoperability, aids in segregating
application domains and more. Type verification occurs during just-in-time
compilation, ensures that MSIL safely accesses memory and confirms that there is no
attempt to access memory that is not formerly defined in metadata. If so, the code is
treated as a rogue application. CTS provides a shared type substratum for .NET,
enhancing language interoperability.

1-7 C# and .NET Programming


.NET Framework

.NET introduces lightweight processes called application domains. Application


domains are processes within a process. Application domains are more scalable and
less expensive than traditional Win32 processes. .NET must police application
domains and guarantee that they are good neighbors. Code verification, type safeness
and CTS play a role in guaranteeing that application domains are safe.
x) .NET Framework Class Library
The .NET Framework Class Library (FCL) is a set of managed classes that provide
access to system services. File input/output, sockets, database access, remoting and
XML are just some of the services available in the FCL. All the .NET languages rely
on the same managed classes for the same services. Therefore, once any .NET
language is learned, it is equivalent to 40 percent learning of any other managed
language. The same classes, methods, parameters and types are used for system
services regardless of the language. This is one of the most important contributions of
FCL.
FCL includes around 600 managed classes. A hierarchy consisting of hundreds of
classes would be difficult to navigate. Microsoft partitioned the managed classes of
FCL into separate namespaces based on functionality. For example, classes pertaining
to local input/output can be found in the namespace System. IO. To further refine the
hierarchy, FCL namespaces are often nested; the tiers of namespaces are delimited
with dots. System.Runtime.InteropServices, System.Security.Permissions and
System.Windows.Forms are examples of nested namespaces. The root namespace is
System, which provides classes for console input/output, management of application
domains, delegates, garbage collection and more.
The following are different types of applications that can make use of .net class
library.
1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.
In short, developers just need to import the class library in their language code and use its
predefined methods and properties to implement common and complex functions like reading
and writing to file, graphic rendering, database interaction and XML document manipulation.

1-8 C# and .NET Programming


.NET Framework

xi) Garbage Collection :


The Garbage collector is .NET’s memory management component. This is a program
whose purpose is to clean up memory. All the dynamically requested memory is
allocated on the heap. This heap is managed by the CLR. When .NET detects that the
managed heap for a given process is becoming full it calls the garbage collector. The
garbage collector runs through variables currently in scope in the code, checks for the
references to objects stored on the heap to see if they can be accessed from the code.
Any objects that do not have any references in the code will be removed.
Garbage Collection works in .NET because MSIL has been designed to facilitate the
process. If any reference to an object exists then there is sufficient information in the
reference to exactly determine the type of the object. Garbage collection is not
deterministic which means it is not guaranted when Garbage Collector will be called,
it will be called when CLR decides that it is needed. GC can be called explicitly
through code.
xii) Other components of .NET framework
1) WinRT : WinRT or Windows Runtime APIs provides the user interface elements for
building Windows Store apps and provides access to Windows 8 or Windows RT OS
features. WinRT supports development in C and other managed languages C# and
VB.NET, as well as JavaScript and TypeScript.
2) Asp.Net : This is used to build rich internet based web application.
3) Desktop Apps (Windows Forms) : A Windows Desktop app is traditional Windows
Forms application with a new name. Software developed for Windows XP, Windows
Vista and Windows 7 will be categorized as a Windows Desktop app when running in
Windows 8. Examples of Windows Desktop apps are Microsoft Office families
products, notepad etc.
4) Window Presentation Foundation :WPF is used to create applications with a rich user
experience. It includes application UI, 2D graphics, 3D graphics and multimedia. It
takes advantage of hardware acceleration of modern graphic cards. WPF makes the UI
faster, scalable and resolution independent.
5) Silver Light : This is a cross-browser web based technology which allows designers
and developers to deliver Rich Internet Applications (RIA) embedded in Web pages.
6) Ado.Net : This is used to create Data Access Layer to query and manipulate data from
underlying data source like SQL Server, Oracle, and DB2 etc.
7) LINQ : This allows to query the data from the various data sources (like SQL
databases, XML documents, Ado.Net Datasets, Various Web services and any other

1-9 C# and .NET Programming


.NET Framework

objects such as Collections, Generics etc.) using a SQL Query like syntax with .Net
framework languages like C# and VB.
8) Ado.Net Entity Framework : This is used to query and store data into to the relational
databases (like SQL Server, Oracle, DB2 etc.) in ORM fashion.
9) Parallel Extension : This allows to distribute work code across multiple processors to
take advantage of the hardware.
10) Windows Communication Foundation : This is used for building and developing
services based on WS-* standards.
11) Asp.Net WebAPI : Asp.Net Web API is a framework for building HTTP services that
can be consume by a broad range of clients including browsers, mobiles, iphone and
tablets.
12) SignalR : ASP.NET SignalR is a library that simplifies the process of adding real-time
web functionality to applications. Real-time web functionality is the ability to have
server code push content to connected clients instantly as it becomes available, rather
than having the server wait for a client to request new data.
13) Windows Workflow Foundation : This is used to build process oriented business
workflow and rules engine.

1.2 The C# Language

Concept
C# Family

1. C# (pronounced "C-sharp") is a simple, modern, general-purpose, complete object-


oriented programming language rom Microsoft within its .NET framework.
2. C# was developed at Microsoft that facilitate the exchange of information and services
over the Web and to enable developers to build highly portable applications.
3. Its initiative was led by Anders Hejlsberg at Microsoft.
4. It is a part of Microsoft Visual Studio since version 7.0.
Explanation
C# Goal

5. C# goal was to combine the computing raw power of C++ with the productivity and
programming ease of Visual Basic.
6. C# is based on C++ and contains features similar to those of Java.

1 - 10 C# and .NET Programming


.NET Framework

C# Platform

7. Visual studio supports Vb, VC++,C++, Vbscript, Jscript and C#. All of these languages
provide access to the Microsoft .NET platform.
8. .NET platform includes a Common Execution engine and a rich class library.
9. Microsoft’s Common language run time(CLR) accommodates more than one languages
such as C#, VB.NET, Jscript, ASP.NET,C ++.
10. The steps followed for code execution is, Source code --->Intermediate Language
code(IL) ---> (JIT Compiler) Native code.
11. The built-in classes and data types are common to all of the .NET languages.
C# can do

12. Using C# one can develop Console application, Windows application, Web application.
13. C# simplifies programming through its use of Extensible Markup Language (XML) and
Simple Object Access Protocol (SOAP). This allows access to a programming object or
method without requiring the programmer to write additional code for each step.
C# being simple

14. There are no pointers in C#.


15. No Direct memory manipulations are supported because generally they are unsafe in
terms of storage access.
16. "::" or "->" operators are not used in C#.
C# memory management

17. Automatic memory management and garbage collection is supported by .NET framework.
C# by default inherits these features of its platform.
18. There are various required ranges of the primitive data types like Integer, Floats etc.
19. Boolean values are pure true or false values in C#. Numeric values 0 and 1 are not used
for true and false. Therefore, errors of "="operator and "=="operator is not encountered.
20. Operator "==" is used for comparison operation and operator "=" is used for assignment
operation.
C# is latest

21. C# has followed current trends and is very powerful in terms of interoperability,
scalability, robustness and web development.
22. It includes built in support for converting any application component into a web service
that can be invoked over the internet from any application running on any platform.

1 - 11 C# and .NET Programming


.NET Framework

C# follows object-oriented paradigm

23. Data abstraction, data encapsulation, inheritance, polymorphism all features are supported
in C# making it complete object oriented language.
24. C# has introduced structures (struct) which enable the primitive types (int, float, double)
to become objects.
C# is type safe

25. Unsafe casting like converting Double to a Boolean is unsupported in C#.


26. Automatic compiler initializations are supported in C#, like, value types (primitive types)
are initialized to zeros and reference types (objects and classes) are initialized to null.
27. In C# arrays are zero base indexed. Array bounds are checked.
28. C# allows for checking the overflow of types.
C# is interoperable

29. C# has complete native support for the COM and windows based applications.
30. C# do allow restricted use of native pointers for supporting applications that are using
pointers. C# allows the users to use pointers as unsafe code blocks to manipulate old code.
31. C# has built in support for implementation of unknown and other COM interfaces.
32. Components from VB.NET and other managed code languages can directly be used in C#.
C# is scalable

33. .NET platform has introduced assemblies which are self describing by means of their
manifest files. These manifest files establish the assembly identity, version, culture and
digital signature. Also, assemblies need not to be registered anywhere.
34. If one needs to scale any application, then it can be done just by deleting the old files and
updating them with new ones. There is no need of registration of dynamic linking library.
C# is updatable

35. A big error prone task in the application’s life is its maintenance. Updating software
components is a crucial and highly time-bound task. The revisions made to the code can
affect the existing program. C# supports the concept of versioning as the language feature.
36. By the language itself, there is a native support for interfaces and method overriding
which enables complex frame works to be developed and evolved over the time.

1 - 12 C# and .NET Programming


.NET Framework

1.3 OOP Concept

Concept

1. Object Oriented Programming (OOP) is a design philosophy. Object-Oriented


Programming (OOP) uses a different set of programming languages than old procedural
programming languages (C, Pascal, etc.). Reusability is attained due to a bundle of self
sustainable thing the ‘object’. Due to ‘object’ concept four main object-oriented
programming concepts have raised.
Explanation

2. Let a ‘hand’ be a class. A human body has two objects of the type ‘hand’, named "left
hand" and "right hand". Their main functions are controlled by a set of electrical signals
sent through the shoulders (which acts as an interface between body and hand). The hand
is a well-architected class. By changing little properties, the hand is being reused to create
the left hand and the right hand.
3. Object Oriented Programming (OOP) is a programming paradigm (a programming
thought process) wherein programs are organized around objects and data rather
than action and logic.
4. OOP allows decomposition of a problem into a number of entities called objects and then
builds data and functions around these objects.
5. OOP Features
1. Class

1. A class is the core of any modern Object Oriented Programming language such as C#.
In OOP languages it is mandatory to create a class for representing data.
2. A class act as a blueprint of an object that contains variables for storing data and
functions to perform operations on the data.
3. A class does not take any memory space as it is only a logical representation of data.
4. Creating Class - To create a class, the keyword "class" is used, followed by the class
name, as shown below,
Example -

1 - 13 C# and .NET Programming


.NET Framework

2. Object

1. An object is an instance of a class. Object is a basic run-time entity of an object


oriented system. It would represent actual place, person, book or any item that the
program is dealing with.
2. An object is a bundle of software of related variable and methods.
3. An object is a real-world entity that keeps together property states and behaviors.
4. To make use of the Class, one must create a variable for the class, which is termed as
object.
5. Object is called as an instance of Class and its starting address is stored in the object
when it is instantiated. In C# language, Object can be instantiated as follows,
Example

3. Abstraction

1. Abstraction is, "To represent the essential feature without representing the background
details."
2. Abstraction tries to focus on what the object does instead of how it does it.
3. Abstraction provides a way to generalize the view of classes or objects by providing
relevant information about them.
4. Abstraction is the process of providing only essential information to the outside real
world and hiding overall background details to present an object.
5. It relies on the separation of interface and implementation.
6. Abstraction solves the problem at the design level.
7. Abstraction is a outer layout, used in terms of design.
8. For example : An external of a microwave oven, it has a display screen with keypad
buttons to set temperature, timer etc.
Example of Abstraction

1 - 14 C# and .NET Programming


.NET Framework

As it can be seen from the above example that necessary methods and properties are
exposed using public access modifier and rest of the methods and properties are hidden using
private access modifier. This way abstraction is achieved in the applications.
4. Information Hiding

1. Information hiding concept restricts direct exposure of the data.


2. Data is accessed indirectly using safe mechanism so as to avoid unwanted handling of
data.
3. Objects and their methods are used for data hiding implementation.
5. Encapsulation

1. Wrapping up a data member and a method together into a single unit (in other words
class) is called Encapsulation.
2. Encapsulation is like enclosing material in a capsule. That is enclosing the related
operations and data related to an object into that object.
3. For example sack can encapsulate bottle, tiffin, files, laptop etc. In a object one
encapsulates data members and functions working around data members.
Example

1 - 15 C# and .NET Programming


.NET Framework

4. Encapsulation means hiding the internal details of an object that how an object does
something.
5. Encapsulation prevents peeping into object’s inside view, where the behaviour of the
abstraction is implemented.
6. Encapsulation is a technique used to protect the information in an object from another
object.
7. By encapsulation the data is hidden for security purpose by making the variables
private and expose the property to access the private data that will be accessed
publicly.
8. Encapsulation solves the problem in the implementation level.
6. Inheritance

1. Inheritance is to create a new class using an existing one that is extending one class
from another.
2. When a class includes and uses a property of another class it is known as inheritance.
3. The main advantage of extending classes is that it provides a convenient way to reuse
existing fully tested code in different context thereby saving lots of time with existing
coding and its model style.
4. Through effective use of inheritance, one can save lot of programming time and also
reduce errors, which in turn will increase the quality of work and productivity.
5. For example, a Batsman includes the properties of Players.
Example

1 - 16 C# and .NET Programming


.NET Framework

Output

7. Polymorphism

1. Polymorphism means one name, many forms. The word Polymorphism means having
many forms. Many forms of a single object is called Polymorphism.
2. Generally, polymorphism can be achieved when there is a hierarchy of classes and
they are related by inheritance.
3. One function is made to behave in different forms based on its invoking object and
parameters to it.
4. There are two types of polymorphism -
Compile time polymorphism :

i) In this polymorphism, compiler identifies which polymorphism form it has to take and
evaluate at compile time only hence, is called as compile time polymorphism or early
binding.
ii) Early binding is achieved by Method Overloading and Operator Overloading. The
Method Overloading means more than one method having same name but different
signatures (or parameters) in the same or different class.
iii) Advantage of early binding is that execution becomes fast because everything about
the method is known to compiler during compilation process itself.
iv) The main disadvantage is it lacks flexibility of runtime decision.
Runtime polymorphism :

i) In this polymorphism, compiler identifies which polymorphism form it has to take and
evaluate at runtime is called as runtime polymorphism or late binding.

1 - 17 C# and .NET Programming


.NET Framework

ii) Late binding is achieved through combining inheritance and Method Overriding. The
Method Overriding means having two methods with same name and same signature,
one method in super (base) class and other method in sub (derived) class. It must
require changing the behavior of the super class methods in sub class to use its
functionality differently.
iii) Major advantage of late binding is that it provides flexibility to adjust object types at
runtime.
iv) In late binding execution becomes slow as compiler has to get the information about
the method to execute at runtime.
v) Example
An Employee behaves as Worker.
An Employee behaves as Supervisor.
An Employee behaves as Manager.
An Employee behaves as Officer.
Here, employee is an object but the behavioral aspects are different in different situations.
8. Constructors
1. Constructors are special methods, used when instantiating a class. A constructor can
never return anything. There is no need to define a return type for it as well.
2. If no constructor is defined then the CLR(Common Language Runtime) will provide
an implicit constructor which is known as a Default Constructor.
3. Constructors can be overloaded. A class can have number of constructors and they
differ in the number of arguments that are passed, that is they should have different
parameters or signatures.
4. References or pointers on constructors are never used because their addresses cannot
be taken.
9. Destructors

1. Since garbage cleanup is automatic system, framework will free the objects that are no
longer in use. Hence destructors in C# are required for clean up work.
2. There may be times where in there is need to do some manual cleanup. In this case
one can use destructor, which is used to destroy the objects that are no longer in use.
3. A destructor method called once an object is disposed.
4. Destructor’s main goal is to cleanup resources used by the object. Destructors don’t
look very much like other methods.
5. When object is collected by the garbage collector, Destructor method is called.

1 - 18 C# and .NET Programming


.NET Framework

Two Marks Questions with Answers

Q.1 How many languages are supported by .NET at present time ?


Ans. : When .NET was introduced first time, it supports many languages like
VB.NET,C#,COBOL and Perl etc. At present time it supports almost 44 languages.
Q.2 What is CTS ?
Ans. : CTS stands for Common Type System. It has a set of rules which state how a data
type should be declared, defined and used in the program. It describes the data types that
are to be used in the application.
We can design our own classes and values by following the rules that are present in the
CTS. The rules are made so that the data type declared using a programming language can
be called by an application that is developed using a different language.
Q.3 What is MSIL ?
Ans. : MSIL stands for Microsoft Intermediate Language.
MSIL provides instructions for calling methods, initializing and storing values,
operations such as memory handling, exception handling and so on. All .Net codes are first
compiled to IL.
Q.4 How is a Managed code executed ?
Ans. : Follow these steps while executing a Managed code :
Choosing a language compiler depending on the language in which the code is
written.
Converting the above code into Intermediate language by its own compiler.
The IL is then targeted to CLR which converts the code into native code with the help
of JIT.
Execution of Native code.
Q.5 What is the difference between managed and unmanaged code ?
Ans. :

Managed code Unmanaged code

Managed code is managed by CLR Any code that is not managed by CLR

.NET framework is necessary to execute Independent of .NET framework


managed code

CLR manages memory management through Own runtime environment for compilation and
garbage collection execution

1 - 19 C# and .NET Programming


.NET Framework

Q.6 What is the .NET Framework ?


Ans. : The .Net framework is a software development platform developed by Microsoft.
The framework was meant to create applications, which would run on the Windows
Platform. The first version of the .Net framework was released in the year 2002.
The version was called .Net framework 1.0. The .Net framework has come a long way
since then, and the current version is 4.7.1.
The .Net framework can be used to create both - Form-based and Web-based
applications. Web services can also be developed using the .Net framework.
Q.7 State the characteristics of C#.
Ans. : Characteristics of C#
Simple : It does not supports –> and pointers. C# treats inter and Boolean as two
different data types .
Consistent : C# supports only one integer type with no limitation of range.
Inter-operability : C# provides the facility to a program to call out any native API. .
Modern : C# contains features as that in modern programming language like
automatic garbage collection, sound security model and a rich intrinsic model for
error handling.
Object oriented : C# is an modern object oriented programming language supporting
encapsulation, inheritance and polymorphism.
Type safe : C# incorporates type safe measures like dynamically allocated objects and
arrays are initialised to zero, not allowing unsafe casts and overflow check during the
arithmetic operations.
Versionable : C# supports versioning of applications developed using it so that on
different versions of same application are available for usage.
Compatible with other Language
C# enforces the .NET common language specifications (CLS) and therefore allows
interoperation with other .NET language.
Q.8 List out the different types of applications that can be created on .net.

Ans. : Below is the list of various types of application that can be developed on .NET.
1. ASP.Net Web applications are programs that used to run inside some web server to
fulfill the user requests over the http. ASP.NET Web applications can range from
simple Web sites that consist of HTML pages to advanced enterprise applications
that run on local and remote networks. These enterprise applications also provide

1 - 20 C# and .NET Programming


.NET Framework

components for exchanging data using XML. This type includes dynamic and data
driven browser based applications. (Ex : Hotmail and Google).
2. Web services are “web callable” functionality available via industry standards like
HTTP, XML and SOAP.
3. Windows applications are form based standard Windows desktop applications for
common day to day tasks. (Ex : Microsoft word). Run only under Windows
environment. These applications consume the services provided by the Windows
operating system.
4. Windows services are long-running executable applications that run on the system as
a background process. These applications do not interfere with the working of the
other processes that run on the same computer. Windows services execute within
separate Windows sessions created specifically for each Windows service. These
services do not have a graphic user interface and are ideal for running on the server.
Windows services were earlier called NT services.
5. Console applications are light weight programs run inside the command prompt
(DOS) window. They are commonly used for test applications.
6. Mobile applications can run on multiple mobile devices, such as Pocket PCs, mobile
phones, or personal digital assistants. These applications provide ubiquitous access to
data from mobile devices. The .NET Framework automatically makes changes to
these applications to enable them to run on multiple browsers, depending on the
mobile device.
7. Class libraries are components that are created once and reuse a number of times in
multiple applications. Class libraries allow to define several classes, along with their
methods and interfaces, in one file. These libraries compile to .dll files and facilitate
rapid development of new applications because of reusability of code. To access the
functionality of the classes in a class library from the application, one needs to
include a reference to that library in the program.
8. Windows Presentation Foundation (WPF) apps - Windows Presentation
Foundation (WPF) provides developers with a unified programming model for
building line-of-business desktop applications on Windows.
9. Service-oriented apps using Windows Communication Foundation (WCF) -
Windows Communication Foundation (WCF) is a unified programming model for
building service-oriented applications. It enables developers to build secure, reliable,
transacted solutions that integrate across platforms and interoperate with existing
investments.

1 - 21 C# and .NET Programming


.NET Framework

10. Workflow-enabled apps using Windows Workflow Foundation (WWF) - WWF


is a programming model that provides way to model process, activities and
workflows.
All types of .NET applications use one or more .NET compliant languages for their
design and development. The .NET Framework includes various technologies, such
as ASP.NET, VB.NET, VC++.NET and ADO.NET. The ASP.NET is used to build
Web applications and services, VB.NET and VC++.NET to create Windows
applications, and ADO.NET for flexible access to databases.
Q.9 Define Marshaling.
Ans. : A .NET code is referred to as “managed” because it is controlled (managed) by the
CLR. Other code that is not controlled by the CLR is called unmanaged.
In context with C# programming, marshaling is the process of creating a bridge
between managed code and unmanaged code; it is the local one that carries
messages from the managed to the unmanaged environment and reverse. It is one of
the core services offered by the CLR (Common Language Runtime). Because much
of the types in unmanaged environment do not have counterparts in managed
environment, one needs to create conversion routines that convert the managed types
into unmanaged and vice versa; and that is the marshaling process.
In ASP .NET context marshaling is a process of transforming or serializing data
from one application domain and exporting it to another application domain.
There are two types of marshalling,
o Marshal by value : A copy of an object is created by the server and is passed
and used by the client.
o Marshal by reference : The client creates a proxy to access the object.

Long Answered Questions

Q.1 Explain .NET architecture. (Refer section 1.1)


Q.2 What are features of .NET features ? (Refer section 1.1)
Q.3 What is JIT and its various types in .NET environment ? (Refer section 1.1)
Q.4 Write a note on C# programming language. (Refer section 1.12)
Q.5 What are OOP features ? (Refer section 1.3)

.NET Framework ends …

1 - 22 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Core C#, Variables, Data Types.

Section No. Topic Name Page No.


2.1 C# Character Set 2-2

2.2 Token 2-3

2.3 Keyword 2-5

2.4 Literals and Constants 2-6

2.5 Identifier 2 - 15

2.6 Naming Convention 2 - 16

2.7 Data Types 2 - 22

2.8 Variable 2 - 25

2.9 Type Conversion and Casting 2 - 29

2.10 Boxing and Unboxing 2 - 32

2.11 First C# Program 2 - 35

2.12 Comment in C# 2 - 38

2.13 Errors in C# 2 - 39

Two Marks Questions with Answers 2 - 41

Long Answered Questions 2 - 43

2-1 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.1 C# Character Set

2.1.1 Basics
Concept

1. The .NET Framework and hence C# uses the UTF-16 encoding (represented by the
UnicodeEncoding class) to represent characters and strings.
Explanation

2. The C# character set conforms to Unicode 3.0, Unicode is a 16-bit character format
designed to represent the many characters sets from all languages worldwide.
3. Any Unicode character can be specified with a Unicode escape sequence, \u or \U,
followed by four hex digits.
4. The most widely used character set among languages has been the American Standard
Code for Information Interchange (ASCII). The basic limitation of ASCII is its 8-bit
character size. This doesn't accommodate multibyte character sets for various international
languages. As the information technology brings people across the globe close making the
world smaller, international considerations must become larger.
5. Unicode's character set includes ALL human language's written symbols. It includes the
tens of thousands Chinese characters, math symbols, as well as characters of dead
languages, such as Egyptian Hieroglyph.
6. The first 128 characters of Unicode (which correspond one-to-one with ASCII) are
encoded using a single octet with the same binary value as ASCII, making valid ASCII
text valid UTF-8-encoded Unicode as well.
2.1.2 Character Set and Encoding System
Concept

1. A char set is a standardized set of characters.


2. A encoding system is a standardized way to transform a sequence of characters (of a given
char set) into a sequence of 0 and 1.
Explanation

3. Unicode defines several encoding system. UTF-8 and UTF-16 are the two most popular
Unicode encoding systems.
4. UTF-8 is suitable for texts that are mostly Latin alphabet letters. For example, English,
Spanish, French, and most web technology such as HTML, CSS, JavaScript. Most Linux's

2-2 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

files are in UTF-8 by default. UTF-8 encoding system is backwards compatible with
ASCII. (meaning: If a file only contain characters in ASCII, then encoding the file using
UTF-8 results the same byte sequence as using ASCII as encoding scheme.)
5. With UTF-16, every char is encoded into at least 2 bytes, and commonly used characters
in Unicode are exactly 2 bytes. For Asian languages containing lots of Chinese characters,
such as Chinese Japanese, UTF-16 creates smaller file size.
6. There's also UTF-32, which always uses 4 bytes per character. It creates larger file size,
but is simpler to parse. Currently, UTF-32 is not being used much.

2.2 Token

Concept

1. Token is the smallest individual unit that is made up of valid characters in C#.
2. Tokens are valid words that are the basic building blocks of C# Programming.
Explanation

3. Token is formed and defined using the C# grammar.


4. Tokens are generally any unit that is not whitespace or a comment.
5. Every C# program is basically collection of tokens.
6. There are 5 kinds of tokens namely, identifiers, keywords, literals, operators, and
punctuators.
7. White space and comments are not tokens, though they act as separators or delimeters for
tokens.

Fig. 2.2.1

Example

2-3 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

In the above program following are the various Tokens (along with their classification),
Token Classification

2-4 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.3 Keyword

Concept

1. Keywords are the language specific, reserved and predefined words that cannot be used as
the identifiers.
Explanation

2. Every C# word is classified as either keyword or identifier.


3. All keywords have a fixed meanings and these meanings cannot be changed.
4. All keywords are lower-case.
5. for, do, while, break, case, if, else, int, char, public, class, union, try are some of the
example of keyword.
6. A keyword is an essential element of a language definition.
7. If anybody wants to use keyword as the identifier then one has to use the "@" as the prefix
of that keyword. For example, 'for' is a keyword if anybody wants to use it as identifier
then one can do so by adding prefix @ to this like "@ for".
8. C# has defined many keywords which are given listed in the following table :

abstract event new struct

As explicit null switch

Base extern object this

Bool false operator throw

Break finally out true

Byte fixed override try

Case float params typeof

Catch for private uint

Char foreach protected ulong

checked goto public unchecked

Class if readonly unsafe

Const implicit ref ushort

continue in return using

2-5 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

decimal int sbyte virtual

Default interface sealed volatile

delegate internal short void

Do is sizeof while

Double lock stackalloc

Else long static

Enum namespace string

9. Contextual Keyword - Contextual keywords have special meaning only in a limited


program context and can be used as identifiers outside that context.

Add alias ascending

Async await descending

Dynamic from get

Global group into

Join let orderby

partial(type) partial(method) remove

Select set value

Var Where (generic type constraint) Where (query clause)

Yield

Table 2.3.1 Contextual keywords

2.4 Literals and Constants

2.4.1 Literals
Concept

1. Literals are the way in which the values that stored in variables are represented.
2. Literals are constant values used in the program.
Explanation
3. Constants are fixed values. The constants refer to fixed values that the program may not
alter during its execution.

2-6 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

4. Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are also enumeration constants as
well.
5. Also, a variable can be declared as constant and its value can not be changed during
execution of the program. Literals are classified as follows,

Fig. 2.4.1 Types of literals

2.4.2 Literal Types


1. Integer Literals

a. An integer Literal is a sequence of digits.


b. Integer Literals can be specified as the number without any fractions.
c. Integer Literal can be of type int, uint, long or ulong.
d. To specify the uint, long and ulong, suffix as u/U, l/L and ul/UL are used
respectively. No suffix is used for the int.
e. An integer literal can be hexadecimal, octal or decimal.
f. To specify hexadecimal and octal integer literals, prefix as 0x/0X and o/O, are used
respectively. No prefix is used for the decimal.
Examples

2-7 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

g. Suffix type integer literals

h. Lowercase suffixes : One can specify lowercase suffixes, such as u, l, ul, f, d and m.
But these are easier to confuse with numbers. The letter 'l' is sometimes seen as the
number 1.
Examples of lowercase suffixes

2-8 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2. Real Literals

a. The Numbers that includes decimal sign is knows as Real Literals or a whole
number followed by a decimal point and the fraction part, is known as Real Literals.
b. Floating Point Literals can be of type floats and double.
c. To specify the float literal suffix f/F is used and for specify the double literal suffix
d/D is used.
d. A floating point Literal may be specified as four types.
whole number an exponent
fractional part decimal part
e. C# also allows scientific notation for floating-point numbers where in its exponent
part is also added in the floating point number.
Example

3. Boolean Literals

There are two types of Boolean Literal values in C#.


true false

2-9 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

4. Character Literal

a. Character literals in C# are enclosed in the single quotes. Like 'a' or 'B'.
b. The character literals are immutable and cannot be changed, but the variables that
store those values simply denote storage locations.
c. Character literal can be a simple single character or a escape sequence.
d. Single character Literals : A single character Literals contains a single character
enclosed within a single quotes(' ').
Example

e. Backslash Character Literals : Escape sequences are the special characters which
have some predefined meaning and start with the backslash character. Following
table contains the various character escape sequences with their meanings :
Constant Meaning(Name)
‘\n’ New-line
‘\r’ carriage return
‘\f’ form feed
‘\t’ horizontal tab
‘\a’ alert
‘\b’ back space
‘\o’ null
‘\v’ vertical tab
‘\\’ back slash
‘\’’ single quote
‘\’’’ Double quote

Table 2.4.1 Backslash character literals


Example

2 - 10 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Output

5. String Literals

a. A string Literals is a sequence of characters enclosed within double quotes(" ").


b. String literals are constant string data.
c. The character may be letters, numbers, spaces and special characters.
d. A string literal have also a format like @"".
Examples

2 - 11 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Output

2 - 12 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

/*Obove program defines six class-level strings on the Program class type. The first string
literal reference is a static variable, it means that it will be referenced in the intermediate
language in method bodies where it is used.*/
/*Note: Using the static string will require the execution engine to resolve the _s1 token in
the metadata. However one can reassign the _s2 variable anywhere in program where it is
accessible, such as in the Main method.*/
/*At @ symbol on strings. Four of the string literals shown in the program are prefixed
with the @ symbol before the quotation marks. This symbol indicates the use of the verbatim
string literal syntax.*/
/* Note : backslash is treated as a character and not an escape sequence when the @ is
used. The C# compiler allows to use real newlines in verbatim literals. Quotation marks
should be encoded with double quotes.*/
The program writes to the screen the contents of the string literals declared throughout the
Program class. Note how the quotation marks are displayed in the s1 and s3 variables. The
double quotes are printed as quotes.Console.WriteLine
Concat. Concatenating string variables in C# programs is done at runtime. On the other
hand, if a string variable is constant and is known at compile-time, the compiler will generate
intermediate language with the concatenations removed.
Next : This program appears to concatenate three strings. When compiled the IL shows
that only one string is used.
string.Concat
Example

2 - 13 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Output

6. Null Literals

a. A null literal contains a null value.


b. The type of a null-literal is the null type.
2.4.3 Declaration of a Constant

a. One should declare the constant before using it into the program.
b. It can be declared with a meaningful name of a specific data type and also with a fixed
value which cannot be altered at the time of execution.
c. One has to declare and initialize a constant at a same time otherwise an error will occur.
d. Here is the syntax for the declaration of the constant,

e. Example of the constant

2 - 14 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Output

2.5 Identifier

Concept

1. Identifiers are arbitrary names in C# program. Identifiers are names used to identify code
elements.
2. The term identifier is usually used for variable names, arrays, name of class, method
names, labels, namespace and interface etc.
Explanation

3. Following are some rules for defining identifiers -


1. Identifiers can have alphabets, underscore and digits characters provided First
character must be an alphabet or underscore. It cannot have more than 511 characters.
2. It has to be declared before it is referred.
3. It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [] {
} . ; : " ' / and \. However, an underscore ( _ ) can be used.
4. It cannot have two consecutive underscores in its name because such identifiers are
used for the implementation
5. White spaces are not allowed in identifier.
6. Identifiers must not start with a Digit.
7. For identifiers Upper case and lower case letters are distinct. That is, good, GOOD &
Good are different identifiers than with each other. This indicates that C# is case
sensitive.
8. Keywords cannot be used as identifier names. If the identifier is a keyword, it must be
prefixed with ‘@’. An identifier prefixed with "@" is called a verbatim identifier.
Although prefixing "@" allows for the use of keywords, which helps in interfacing
with other programming languages, it is not a recommended practice.
9. More than one identifier with the same name cannot be declared within a single scope
Example

The following names are valid identifiers in C#

2 - 15 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.6 Naming Convention

Concept

A naming convention is a rule to follow so as to decide what to name identifiers (e.g. class,
package, variable, method, etc.).
Explanation
Why Naming Conventions

By using standard naming conventions one can make self written code easier to read for
themselves and for other programmers. Readability of code is important because it means less
time is spent trying to figure out what the code does, leaving more time to fix or modify it.
To illustrate the point it's worth mentioning that most software companies will have a
document that outlines the naming conventions they want their programmers to follow. A new
programmer who becomes familiar with those rules will be able to understand code written by
a programmer who might have left the company many years before hand.
Picking a Name for Identifier

When choosing a name for an identifier make sure it's meaningful.


Word Choice

The Do’s
1. DO choose easily readable identifier names.
For example, a property named BackGroundColor is more English-readable than
ColorBackGround.
2. DO favor readability over brevity. The property name CanAlignRight is better than
AllignRightX (an obscure reference to the X-axis).

2 - 16 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

3. DO use semantically (meaningwise) interesting names rather than language-specific


keywords for type names.
4. Do use PascalCasing for class names and method names.

5. Do use camelCasing for method arguments and local variables.

6. Do use PascalCasing for abbreviations which are 3 characters or more (2 chars are both
uppercase) as it is consistent with the Microsoft's .NET Framework. The Caps would grab
visually too much attention.

7. Do use predefined type names for data types instead of system type names like Int16,
Single, UInt64, etc. This makes code more natural to read.

2 - 17 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

8. Do use implicit type var for local variable declarations except for primitive types (int,
string, double, etc) for which predefined names can be used. It avoids mess, particularly
with complex generic types. Type is easily detected with Visual Studio tooltips.

9. Do use noun or noun phrases to name a class as it is easy to remember.

10. Do prefix interfaces with the letter I. Interface names are noun (phrases) or adjectives.
This goes consistent with .NET framework.

11. Do name source files according to their main classes. This makes sense as files are
alphabetically sorted and partial classes remain adjacent which is consistent with the
Microsoft practices. Exceptional case is, file names with partial classes reflect their source
or purpose, e.g. designer, generated, etc.

2 - 18 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

12. Do organize namespaces with a clearly defined structure which is useful to maintain good
organization of code base.

13. Do vertically align curly brackets. It is not as per Microsoft standard, but developers have
overwhelmingly preferred vertically aligned brackets.

14. Do declare all member variables at the top of a class, with static variables at the very top
which is generally accepted practice that prevents the need to search for variable
declarations.

15. Do use singular names for enums. Exceptional case is of bit field enums. This is
consistent with the Microsoft's .NET Framework and makes the code more natural to read.
For flags plurals can be used because enum can hold multiple values (using bitwise 'OR').

2 - 19 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

The Don’ts
1. DO NOT use underscores, hyphens, or any other non-alphanumeric characters.
2. DO NOT use Hungarian notation.
3. AVOID using identifiers that conflict with keywords of widely used programming
languages.
4. DO NOT use abbreviations or contractions as part of identifier names. For example, use
GetName rather than GetNm.
5. DO NOT use any acronyms that are not widely accepted, and even if they are, only when
necessary.
6. Don’t use Hungarian notation or any other type identification in identifiers. Other
notations are not consistent with the Microsoft's .NET Framework and Visual Studio IDE.
The compatible notation makes types determination very easy (via tooltips). In general
one should avoid type indicators in any identifier.

7. Do not use Screaming Caps for constants or readonly variables. consistent with the
Microsoft's .NET Framework. Caps grap too much attention.

2 - 20 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

8. Do not use Abbreviations. There are exceptions for certain abbreviations like
abbreviations commonly used as names, such as Id, Xml, Ftp, Uri. It is consistent with
the Microsoft's .NET Framework and prevents inconsistent abbreviations.

9. Do not use Underscores in identifiers. Exceptional case is when one may need to prefix
private static variables with an underscore. It is consistent with the Microsoft's .NET
Framework and makes code more natural to read. Also avoids underline stress of inability
to visualize underscore.

10. Do not explicitly specify a type of an enum or values of enums (except bit fields). It helps
to avoid confusion when relying on actual types and values.

2 - 21 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

11. Do not suffix enum names with Enum which is consistent with prior rule of no type
indicators in identifiers.

2.7 Data Types


Concept

1. The type of data that a variable contains is called Data Type (type). A Data Type is a
classification of things that share similar type of qualities or characteristics or behavior.
Explanation

2. C# is a strongly typed language, it is required to inform the compiler about which data
types is used at the declaration of a variable or object.
3. There are two types of data type in C#
3.1) primitive types (or) predefined which are byte, short, int, float, double, long ,char,
bool, DateTime, string, object etc..
3.2) non-primitive types (or) User Defined which are class, struct, enum, interface,
delegate, array.

2 - 22 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

4. C# Datatypes
Category Data .NET Represents Size (bits) Range (values) Default
type Type value
Name (class/
structure
name)

Integer

byte Byte
8-bit 8 0 to 255 0
Unsigned
integer
sbyte SByte
8-bit Signed 8 -128 to 127 0
integer
int Int32
32-bit Signed 32 -2,147,483,648 to 0
integer 2,147,483,647
uint UInt32
32-bit 32 0 to 4294967295 0
Unsigned
integer
short Int16
16-bit Signed 16 -32,768 to 32,767 0
integer
ushort UInt16
16-bit 16 0 to 65,535 0
Unsigned
integer
long Int64
64-bit Signed 64 -9,223,372,036,854,775,808 0L
integer to
9,223,372,036,854,775,807

ulong UInt64
64-bit 64 0 to 0L
Unsigned 18,446,744,073,709,551,615
integer
Float

float Single
32-bit Single- 32 -3.402823e38 to 0.0F
precision 3.402823e38
floating point
type

2 - 23 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

double Double
64-bit 64 -1.79769313486232e308 to 0.0D
Double- 1.79769313486232e308
precision
floating point
type
decimal Decimal
128 bit 128 (+ or -)1.0 x 10e-28 to 7.9 x 0.0M
Precise 10e28 that is (-7.9 x 1028 to
fractional or 7.9 x 1028) / 100 to 28
integral type
that can
represent
decimal
numbers with
29 significant
digits
Character

char Char
16-bit A 16 Unicode symbols used in '\0'
single text U +0000 to U +ffff
Unicode
character.
string String
A sequence of Instance
characters specific
size varies
Other

bool Boolean
Logical 8 True or False FALSE
Boolean type

object Object
Base type of instance
all other types specific

Date Date
Represents 0:00:00am 1/1/01 to
Time Time
date and time 11:59:59pm 12/31/9999
System
Platform
.IntPtr
dependent

Table 2.7.1 C# Data types

2 - 24 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.8 Variable

Concept

1. A variable is a storage room where in data is actually stored.


Explanation

2. Defining variable

Here, data_type must be a valid C# data type including char, int, float, double, or any user-
defined data type, and variable_list may consist of one or more identifier names separated by
commas.
Example

3. Initializing variables
3.1) Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is:

3.2) Variables can be initialized in their declaration. The initializer consists of an equal
sign followed by a constant expression as:

Examples

3.3) It is a good programming practice to initialize variables properly, otherwise


sometimes program may produce unexpected result.
4. At the time of declaration visibility can be assigned to the variable, and perhaps a value
can also be assign to it at the same time. This can be done as follows,

2 - 25 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Example

5. Lvalue and Rvalue Expressions in C#:


5.1) There are two kinds of expressions in C#
5.1.1) lvalue - An expression that is an lvalue may appear as either the left-
hand or right-hand side of an assignment.
5.1.2) rvalue - An expression that is an rvalue may appear on the right- but
not left-hand side of an assignment.
5.2) Variables are lvalues and hence they may appear on the left-hand side of an
assignment.
5.3) Numeric literals are rvalues and hence they may not be assigned and can not appear
on the left-hand side.
5.4) Following is a valid C# statement :

But following is not a valid statement and would generate compile-time error:

6. Size of the variable


6.1) To get the exact size of a type or a variable on a particular platform, one can use the
sizeof method.
6.2) The expression sizeof(type) yields the storage size of the object or type in bytes.
Following is an example to get the size of int type on any machine,

7. Types of variable
Concept

In C#, based on what a variable contains there are following types of variable namely,
1. value types 2. reference types 3. pointer types
Explanation
7.1 Value types

7.1.1) A variable holds actual values then that type of variables are value
types.
7.1.2) Value type variables can be assigned a value directly. They are
derived from the class System.ValueType.

2 - 26 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

7.1.3) These value types are stored in “stack” memory and these value types
are fixed in size. If a value assigned to a variable is reassigned to
another variable it will create two copies.
7.1.4) Value type variables are of byte, short, int, float, double, long ,char,
bool, DateTime.
7.1.5) Primitive data types are value types except string, object.
7.1.6) Object type is superior to all types. It can store any type or any size of
data. It helps in inheritance process.
7.1.7) Struct, enum are value types.
7.2 Reference types

7.2.1) Reference type is the one in which a variable holds a reference to the
value. The reference types do not contain the actual data stored in a
variable, but they contain a reference to the variables.
7.2.2) In other words, they refer to a memory location. Using multiple
variables, the reference types can refer to a memory location.
7.2.3) If the data in the memory location is changed by one of the variables,
the other variable automatically reflects this change in value.
7.2.4) These reference types are stored in “heap” memory and these types
are not fixed in size. They are maintained in system managed heap
but it also use stack to store reference of the heap.
7.2.5) Example of built-in reference types are: object, dynamic, and string.
7.2.5.1) Object Type
i) The Object Type is the ultimate base class for all data types in C#
Common Type System (CTS).
ii) Object is an alias for System.Object class.
iii) 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.
iv) When a value type is converted to object type, it is called boxing and
on the other hand, when an object type is converted to a value type, it
is called unboxing.
v) Example

2 - 27 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

7.2.5.2) Dynamic Type


i) One can store any type of value in the dynamic data type variable.
ii) Type checking for these types of variables takes place at run-time.
iii) Syntax for declaring a dynamic type is,

ivi) 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.
7.2.5.3) String Type
i) The String Type allows assign any string values to a variable.
ii) 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.
iii) Example
String name = "Anil Kumble";
A @quoted string literal looks as follows,
@"Anil Kumble";
7.2.6) The user-defined reference types are namely,

7.3 Pointer Type

7.3.1) Pointer type variables store the memory address of another type. Pointers in
C# have the same capabilities as the pointers in C or C++.
7.3.2) Syntax for declaring a pointer type is,

Example

2 - 28 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.9 Type Conversion and Casting


Concept

1. Type conversion is a way or method to convert one data type into another data type.

2 - 29 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Explanation

2. In C# type conversion can be done in following two ways:


i. Implicit Type Conversion
ii. Explicit Type Conversion
2.1) Implicit Type Conversion
Concept

1. In implicit type conversion method one data type is converted into another data type
automatically.
Explanation

2. There is no data loss in the Implicit Type conversion therefore it is a type safe conversion.
3. Implicit Type Conversion is generally recommended and used where smaller data type is
converted into larger data type.
Example

Output

2 - 30 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.2) Explicit Type Conversion


Concept
1. In explicit Data Type Conversion method one data type is converted into another data
type with the help of some predefined functions.
Explanation

2. Explicit type conversion is carried out with the help of casting.


3. In explicit type of conversion data loss occurs as the conversion is done forcefully. Hence
it is not a type safe conversion.
Example

Output

In this example ToString method is used in order to convert float value into string. It is a
built-in type conversion method.

2 - 31 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

3. Built-in Methods of Type Conversion in C#

Listed below are various type conversion methods which are widely used in C#.
Method Description

ToBoolean This method converts a data type to Boolean data type.

ToByte This method converts a data type to Byte data type.

ToChar This method converts a data type to Char data type.

ToDateTime This method converts a data type to (Integer or String) to date-time format.

ToDecimal This method converts a data type to (Integer or Float) to decimal type.

ToDouble This method converts a data type to Double data type.

ToInt16 This method converts a data type to 16-bit integer

ToInt32 This method converts a data type to 32-bit integer.

ToInt64 This method converts a data type to 64-bit integer

ToSByte This method converts a data type to Signed Byte type.

ToSingle This method converts a data type to small floating point number.

ToSting This method converts a data type to Sting type.

ToType This method converts a data type to specific type.

ToUInt16 This method converts a data type to Unsigned 16-bit integer.

ToUInt32 This method converts a data type to Unsigned 32-bit integer.

ToUInt64 This method converts a data type to Unsigned 64-bit integer.

Table 2.9.1 Built-in-methods of type conversion in C#

2.10 Boxing and Unboxing


1. Boxing and unboxing are specific types of type-conversion in C#.
2. Boxing
Concept

2.1 Boxing is the process of converting a value type to the type object or to any interface
type implemented by this value type.

2 - 32 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2.2 Boxing is an implicit conversion of a value type to the type object or to any interface
type implemented by this value type.
Explanation
2.3 Boxing is used to store value types in the garbage-collected heap. Boxing a value type
allocates an object instance on the heap and copies the value into the new object.
2.4 When the CLR boxes a value type, it wraps the value inside a System.Object and stores it
on the managed heap.
Example

The integer variable n, is value type variable, that is boxed and assigned to object obj.

The result of boxing statement is creating an object reference obj, on the stack, that
references a value of the type int, on the heap.
This value is a copy of the value-type value assigned to the variable n. The difference
between the two variables, n and obj, is illustrated in the following program.
2.5 It is also possible to perform the boxing explicitly. This is illustrated as in the following
example, but generally, explicit boxing is never required.

Example

2 - 33 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Output

Above example converts an integer variable n to an object obj by using boxing. Then,
the value stored in the variable n is changed from 784 to 879. Example illustrates that the
original value type and the boxed object use separate memory locations, and therefore can
store different values.
3. Unboxing
Concept

3.1 Unboxing is an explicit conversion from the type object to a value type or from an
interface type to a value type that implements the interface.
Explanation

3.2 An unboxing operation consists of,


Checking the object instance to make sure that it is a boxed value of the given value type.
Copying the value from the instance into the value-type variable.
3.3 Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit.
Example

The object obj can then be unboxed and assigned to integer variable n as follows,

3.4 For the unboxing of value types to succeed at run time, the item being unboxed must be a
reference to an object that was previously created by boxing an instance of that value
type.
3.5 Exceptions raised - Attempting to unbox null causes a NullReferenceException.
Attempting to unbox a reference to an incompatible value type causes an
InvalidCastException.
Example

2 - 34 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Output

4. The concept of boxing and unboxing underlies the C# unified view of the type system in
which a value of any type can be treated as an object.
5. Performance - In relation to simple assignments, boxing and unboxing are
computationally expensive processes. When a value type is boxed, a new object must be
allocated and constructed. To a lesser degree, the cast required for unboxing is also
expensive computationally.

2.11 First C# Program

A C# program parts
1. Namespace declaration
2. A class
3. Class methods
4. Class attributes
5. A Main method
6. Statements and Expressions
7. Comments

2 - 35 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

The Programming Example

Output

Explanation

Statement 1 to 4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Above statements are used for including C# class library. C# has huge collection of classes
and objects. If one wants to use those classes then one will have to include their library name
in the program. A program generally has multiple using statements.

2 - 36 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Statement 5
Related classes are kept together under one collection called namespace. Here,
First_c_sharp_program is the namespace.
Statement 7
As C# is completely object oriented programming language, every program must contain at
least one class inside which code is written. First_Program is the class name in the program.
Classes generally contain multiple methods. Methods define the behavior of the class.
However, the First_Program class has only one method Main.
Statement 9
Main() is the method in the class from where the program execution would begin. Main
method, which is the entry point for all C# programs. The Main method states what the class
does when executed.
Statement 12
string name; //Variable for storing string value. It is a string variable that stores value input
by user. A variable is a symbolic name of special data types that is used to store value in
memory temporarily. Here, name is variable of string data stypes.
Statement 15, 19
Console.WriteLine("Enter Your Name");
It is used for displaying message on console. WriteLine is a method of the Console class
defined in the System namespace. This statement causes the message "Enter Your Name" to be
displayed on the screen.

A new thing in this line is {0}. It is pronounced as place holder that is used for displaying
variable value. In the above line, {0} print the value of name.
Statement 17

Console.ReadLine() method is used for accepting user input and then this value is stored in
the name variable.
Statement 11, 13, 14, 16, 18
These statements are ignored by the compiler and they are used to add comments in the
program. /*….*/ is a multi-line comment where as //…. is a single line comment.
Statement 6 and 22, 8 and 21, 10 and 20
These are code block beginning and ending marks depicted by pairs of curly bracket that is
{and}.

2 - 37 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Compiling and Executing the Program

Entering code
Use Visual Studio.Net for compiling and executing C# programs, follow the steps.
1. Start Visual Studio 2010.
2. On the menu bar, choose File -> New -> Project.
3. Choose Visual C# from templates, and then choose Windows.
4. Choose Console Application.
5. Specify a name for project and click OK button.
6. This creates a new project in Solution Explorer.
7. Write code in the Code Editor.
8. Click the Run button or press F5 key to execute the project. A Command Prompt
window appears that contains the line Hello World.
Compiling code using command line
One can compile a C# program by using the command-line instead of the Visual Studio
IDE.
1. Open a text editor and add the above-mentioned code.
2. Save the file as FirstProgram.cs
3. Open the command prompt tool and go to the directory where the file is saved.
4. Type csc FirstProgram.cs and press enter to compile the code.
5. If there are no errors in the code, the command prompt goes to the next line and
generates FirstProgram.exe executable file.
6. Type FirstProgram to execute the program.
7. Output can be seen on the screen.

2.12 Comment in C#

Concept

1. A comment is text that is put somewhere for a human to read, that the compiler ignores.
Explanation

2. Comments are ways for adding text for other developers, non-developers (and self) to
read that the computer ignores. The code after the double forward slash is simply ignored
by the compiler.

2 - 38 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

3. Types of comment -
The are following types of comments in C#
Single line comments

Multiple line comments

XML tags comments

4. General tips to Comment the code


1. Always keep the comments simple and direct.
2. Use comments only for portions of code that are difficult to understand
3. Comments are used to help document what a program does and what the code with it
does. Avoid ASCII art, jokes, poetry and hyper verbosity.
4. It should be made sure that comments are correct and up-to-date.
5. There should consistent style of commenting and Commenting should be done while
writing the code. Add comments while writing code and it's fresh in one’s memory.
6. Finally, important point is that, code should be written in such a way that everyone
should easily understand it.

2.13 Errors in C#

Concept

Errors refer to the mistake or faults which occur during program development or execution.
There are majorly three types of errors a C# programmer may have to face and fix.
Explanation
Following are the expected errors in C# program,

1. Design-time errors 2. Run-Time errors 3. Logical errors


1. Design-Time errors (Syntax errors)

1. Design-Time errors are the ones that are due to incorrectly written programming
statements that is language syntax are not followed properly. The program won't run
at all, with design time errors.
2. Design-Time errors are easy find as C# editor would mark these errors by
underlining them with a wavy coloured line. There are three different colour
markings are done by C# editor namely, blue, red and green. The blue wavy lines

2 - 39 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

are known as Edit and Continue issues, meaning that changes can be made in the
program without having to stop the program. Red wavy lines are clearly the syntax
errors, such as a missing semicolon at the end of a line or spelling mistake in
keyword like ‘while’ as ‘wile’. Green wavy lines are Compiler Warnings.
Warnings are indicative of something that could potentially cause a problem, such
as declaring a variable that's never used, which is misuse of memory.
2. Logical Errors

1. A logic error occurs when the program (the code) is written fine but the result it
produces is not reliable. A logic error is called a bug. With a logic error, the Code
Editor does not see anything wrong in the program code and therefore cannot mark
it. The worse types of logic errors is one that makes a computer crash sometimes,
regularly, or unpredictably.
2. Logic errors are difficult to spot as well to correct. These errors are difficult to spot
because one should be exactly sure about the outcome of the program. One of the
techniques that can be used for tracing logical error is debugging.
3. Debugging is the process of examining code to look for bugs or to identify
problems. Debugging is the ability to monitor the behavior of a variable, a class, or
its members throughout a program. Microsoft Visual C# provides many features to
perform debugging operations. The code or application that is undergoing
debugging is called the debuggee.
4. The longer the code becomes would make its tracing more difficult. Therefore,
making code in modules is good programming practice.
3. Run time errors

1. Run-Time errors are ones that crash the programme in the middle of its execution.
These are also called exceptions. This can be caused due to improper user inputs,
improper design logic or system errors.
2. The program itself generally starts up OK. It's when one tries to do something that
the error is raised up resulting in the abrupt stopping of execution. For example,
dividing a number by zero. a A common Run-Time error is trying to divide by
zero.
3. Exception handling is a mechanism to detect and handle run time errors. C# supports
exception handling extensively and it is achieved by using Try-Catch-Finally blocks
and throw keyword.

2 - 40 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

Two Marks Questions with Answers

Q.1 What is the difference between namespace and assembly ?


Ans. : An assembly is a physical grouping of logical units whereas namespace groups
classes. Also, a namespace can span multiple assemblies as well.
Q.2 Explain the differences between value type and reference type.
Ans. : Following are the main differences between value type and reference type :
Value type contain variable while reference type doesn't contain value directly in its
memory.
In reference type, memory is allocated in managed heap and in value type memory
allocated in stack.
Reference type ex-class value type-struct, enumeration
Q.3 What is variable and constant in .NET programming language ?
Ans. : Variable : A variable is a data storage location in the computer memory that
contains a value and has a meaningful name. Every variable is attached to a data type
which determines what type of value can be stored in the variable.
Variables can be declared by using the following syntax :

Constant : Constant is also similar to the variable except that the value. Value once
assigned to a constant can't be changed. Constants must be initialized at the same time they
are declared.
Constants can be declared by using the following syntax:

Q.4 What is an Escape Sequence ? Name some String escape sequences in C#.
Ans. : An Escape sequence is denoted by a backslash (\). The backslash indicates that the
character that follows it should be interpreted literally or it is a special character. An escape
sequence is considered as a single character.
String escape sequences are as follows :

Q.5 What are nullable types in C# ?


Ans. : C# provides a special data types, the nullable types, to which you can assign normal
range of values as well as null values.

2 - 41 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

For example, you can store any value from – 2,147,483,648 to 2,147,483,647 or null in
a Nullable <Int32> variable. Similarly, you can assign true, false, or null in a Nullable
<bool> variable.
Q.6 C# called C sharp why ?
Ans. : The term "sharp" is inspired by music notation that indicates that the musical note
should be higher in pitch. This has been applied to the language C++, where "++" indicates
that its performance will ideally be improved or increased by 1. The sharp symbol
resembles four "+" symbols (in a grid of two-by-two), that may imply to some that C# is an
advanced or improved version of C++. We have the most extensive question bank to help
you answer C# interview questions.
Q.7 Name the different types of value types in C#.
Ans. : Following are the different types of value in C# :
float
long
int
decimal
double
byte
enum
Q.8 Why Data types are important ?
Ans. :
Data types specify the type of data that a valid C# variable can hold. C# is a strongly
typed programming language because in C#, each type of data (such as integer,
character, float, and so forth) is predefined as part of the programming language and all
constants or variables defined for a given program must be described with one of the
data types. It means one must declare the type of a variable which indicates the kind of
values it is going to store such as integer, float, decimal, text, etc.
Data types are especially important in C# because it is a strongly typed language. This
means that all operations are type-checked by the compiler for type compatibility. Illegal
operations will not be compiled. Thus, strong type checking helps prevent errors and
enhances reliability.
Q.9 Is object a universal data type ? Justify your answer.
Ans. :
Object class supports all classes in the .NET class hierarchy and provides low-level
services to derived classes. This is the ultimate base class of all .NET classes; it is the

2 - 42 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

root of the type hierarchy. All the primitive data types are convertible to Object class
instance and vice-a -versa. Hence it is true that Object is a universal data type.
Q.10 Relate boxing and unboxing.
Ans. :
Basis for Comparison Boxing Unboxing

Basic It converts value type into an It converts an object type


object type. into value type.

Storage The value stored on the stack is The object's value stored on
copied to the object stored on the heap memory is copied
heap memory. to the value type stored on
stack.

Conversion It is implicit conversion process. It is explicit conversion


process.

Example int num = 100; int num = (int) obj;

object obj = num;

Long Answered Questions

Q.1 What is a C# identifier ? (Refer section 2.5)


Q.2 What is boxing and unboxing ? (Refer section 2.10)
Q.3 Write a note type conversions and casting. (Refer section 2.9)
Q.4 What are naming conventions followed in C# ? (Refer section 2.6)
Q.5 How comments are given in C# program ? (Refer section 2.12)
Q.6 Brief the processes boxing and unboxing with example. Refer section 2.10)

Q.7 Explain type conversion and casting. (Refer section 2.9)


Q.8 Explain boxing and unboxing. (Refer section 2.10)
Q.9 With examples explain the various data types in C#.
(Refer section 2.7)

Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing ends …

2 - 43 C# and .NET Programming


Core C# - Part I - Variables, Datatypes, Type Conversion, Boxing-Unboxing

2 - 44 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Core C#.

Section No. Topic Name Page No.


3.1 Operators 3-2

3.2 Classification of Operators 3-2

3.3 Punctuators and Special Symbol 3 - 13

3.4 Operator Precedence and Associativity 3 - 13

3.5 Expression 3 - 16

3.6 Checked and Unchecked Operator 3 - 20

Two Marks Questions with Answers 3 - 22

Long Answered Questions 3 - 23

3-1 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

3.1 Operators

Concept

1. Operator is a symbol that instructs computer to perform specific mathematical or logical


actions.
Explanation

2. Operators are used in programs to manipulate data and variables.


3. Operators allow the processing on the primitive data types and objects.
4. Operators take one or more operand as input and give a result after applying operation
over them. Like in "num1 + num2", 'num1' and ‘num2' are the operands and '+' is an
operator which performs the add operation on 'num1' and 'num2' operands.
5. C# language supports rich set of built in operators. Following are some of the operators,
+-=><*/

3.2 Classification of Operators


Concept

1. Based on the operands involved, method of manipulation, the result of the operation , the
operators are classified in various categories.
Explanation

2. In C# the operators are divided into following categories.


Operators Description

Arithmetic Operators Used to perform simple mathematical operations.

Assignment Operators Used to assign value to the variables.

Bitwise Operators Used to perform operation on binary representation of numerical


data.

Logical Operators Perform operation on Boolean data types or Boolean expressions.

Relational Operators Used for the comparison between two variables or constants.

Miscellaneous Other Various other operations like new, sizeof, ? etc.


Operators

3-2 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

3.2.1 Arithmetic Operators


Concept

1. Arithmetic Operators are the simplest operators used for the purpose of mathematical
operation like addition, subtraction etc.
Explanation

2. Following is the list of all arithmetic operators in C#.


Arithmetic Meaning Example Associativity
Operators
+ ‘Addition operator’ used num1 + num2 = 30 Left to right
to add two operands.
– ‘Subtraction operator’ num1 - num2 = -10 Left to right
used to subtract second
operand from first.
* ‘Multiplication num1 * num2 = 200 Left to right
operator’ used to
multiply two operands.
/ ‘Division operator’ used num2 / num1 = 2 Left to right
to divide numerator by
de-numerator.
% ‘Modulus operator’ used num1 % num2 = 0 Left to right
to find remainder after
division.
++ ‘Increment operator’ num1++ = 11 Right to left
used to add one to the
operand.
–– ‘Decrement operator’ num1-- = 9 Right to left
used to subtract one
from the operand

Example

3-3 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Output

3-4 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

3.2.2 Relational Operators


Concept

1. Relation operators are used for the relative comparison between two values.
Explanation

2. Here is the list of table containing the various relational operators


Relational Operator Description Example

< Is less than 10<20 is true

<= Is greater or equal to 10<=5 is false

> Is greater than 5>2 is true.

>= Is greater than or equal to 2>=2 is true.

== Is equal to 5= = 12 is false.

!= Is not equal to 5!=12 is true.

Example

3-5 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Output

3.2.3 Logical Operators


Concept
1. Logical operators perform operation on boolean expression or boolean data type values.
Explanation
2. Following is the list of all logical operators in C#.
Logical Operators Description

&& Logical And Operator, Perform And operation between two


Boolean expression.

|| Logical Or Operator, Perform Or operation between two


Boolean expression.

! Logical Not Operator, Find out the complement or any Boolean


expression.

3. Following is the set of truth table for each logical operator.

Operand1 Operand2 Operand1&&Operand2

true true true

true false false

false true false

false false false

Table 3.2.1 Logical And Operator (&&)

3-6 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Operand1 Operand2 Operand1 | | Operand2


true true true
true false true
false true true
false false false

Table 3.2.2 Logical Or Operator (||)

Operand !Operand
true false
false true

Table 3.2.3 Logical Not Operator(!)


Example

3-7 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Output

3.2.4 Bitwise Operators


Concept

1. Bitwise operators perform operation on the binary representation of a numeric value.


Explanation

2. Here is the list of Bitwise operators in the given table.


Bitwise Operators Description

& (Bitwise And operator) This operator copies a bit to the result if it exists in both
operands.

| (Bitwise Or operator) This operator copies a bit to the result if exists in either
of the operand.

~ (Bitwise Not operator) This operator complement the value of the bit on which it
is applied.

^ (Bitwise Xor Operator) This operator copies the bit if it is set in one operand but
not both.

<< (Bitwise Left Shift Operator) The left operands value is moved left by the number of
bits specified by the right operand.

>> (Bitwise Right Shift Operator) The left operands value is moved right by the number of
bits specified by the right operand.

Example

3-8 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Output

3.2.5 Assignment Operators


Concept

1. Assignment operators are used to assign values to variables in the program.


Explanation

2. Following is a list of Assignment operators.


Assignment Operators Description Example

= (simple Assignment Operator) Assign the value of right x=y; assign the value of
operand to left operand. x variable to y.

+=(Add and assignment operator) Add the value of right operand x+=y; add the value of
and left operand and then x and y variable and
assign the result to left operand. assign its result to x
variable.

3-9 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

=(subtract and assignment operator) Subtract the value of right x–=y; subtract the value
operand from the left operand of y variable from x
and then assign the result to left variable and assign its
operand. result to x variable.

/= (divide and assignment operator) It performs division by taking x/=y; divide the value
left operand as numerator and of y variable by value
right operand as de-numerator of x variable and assign
and assigns the result to left its result to x variable.
operand.

= (multiply and assignment It performs multiplication x = y; multiply the


Operator) between left operand and right value of y variable and
operand and then assigns the x variable and assign its
result to left operand. result to x variable.

%= (modulus and assignment It finds out the modulus of two x%=y; find the
operator) operands and then assigns the modulus of values of x
result to left operand. and y variables and
then assign the result to
x variable.

Example

3 - 10 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Output

3.2.6 Miscellaneous Other Operators


Concept

1. In C# there are several other operators which are used for performing language specific
operations like type checking (operator type or operator ‘is’), ternary conditional checking
(operator ?:) , finding size of variable(operator sizeof), member access operator etc.
Explanation

2. These operators are listed in below table.


Operators Description

? : (Conditional operator) Condition? x:y, If condition is true then return x


otherwise return y.

. (access operator) “.” (dot) is used to access the member fields of


methods of a class or object.

(type) Type conversion operator) This operator is used to convert one data type to
another data type.

‘sizeof’ operator Return the size of a data type.

3 - 11 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

‘??’ operator The operator ‘??’ is similar to the conditional


operator? :. The difference is that it is placed between
two operands and returns the left operand only if its
value is not null, otherwise it returns the right operand.

‘is’ operator Determines object id of certain type

Example

3 - 12 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Output

3.3 Punctuators and Special Symbol

Concept

1. Symbols are those characters other than the Alphabets, Digits and white-spaces.
Explanation

2. Punctuators are the symbols that are used for grouping and separating the code. They
define the structure of the program.
3. Punctuators are also known as separators.
4. Following is list of punctuators,
1. Semicolon(;)
2. colon(:)
3. Comma (,)
4. period (.)
5. parentheses ( )
6. Brackets [ ]
7. Braces { }

3.4 Operator Precedence and Associativity

Concept

1. When evaluating C# expressions, there are certain rules to ensure the correct outcome of
the evaluation.
2. These rules are governed by precedence and associativity, and preserve the
semantics/meaning of all C# expressions.
Exaplantion

3. Precedence refers to the order in which operations should be evaluated.


4. Operator precedence defines the ordering of operators according of its priority.
5. Sub-expressions with higher operator precedence are evaluated first.
6. Each operator has different priority level based on its operation.

3 - 13 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

7. For example, in a expression n3 = n1 +n2 /n4; , operator '/' has the highest precedence
and operator '=' has the lowest precedence. So, '/' will be operated first, '+' will be
operated after that and lastly '=' will be operated.
8. Mathematical operations are evaluated as per BODMAS rule precedence.
9. There are some operators whose precedence is same.
10. If such operators are in same expression, then it will be evaluated according to its
associativity.
11. There are two types of associativity, namely, left and right.
12. Operators with left associativity are evaluated from left to right. When an operator has
right associativity, its expression is evaluated from right to left.
13. For example, the assignment operator is right-associative. Therefore, the expression to its
right is evaluated before the assignment operation is invoked. Also,
in a expression n3 = n1 +n2 – n4; operator ‘+’ and ‘–‘ have same precedence, so, it will
be evaluated according to its accociativity which is left to right in case of the additive
associativity, So, operator ‘+’ will be operated before ‘–‘.
14. The precedence and associativity of C operators affect the grouping and evaluation of
operands in expressions.
15. An operator's precedence is meaningful only if other operators with higher or lower
precedence are present.
16. Precedence can also be described by the word "binding." Operators with a higher
precedence are said to have tighter binding.
17. Certain operators have precedence over others to guarantee the certainty and integrity of
computations. One effective rule of thumb when using most operators is to remember
their algebraic precedence.
18. Operators according to their precedence (Highest priority to lowest priority) with their
associativity is listed below.
1. Primary Operators 2. Unary Operators
3. Multiplicative Operators 4. Additive Operators
5. Shift Operators 6. Relational and Type Operators
7. Equality Operators 8. Bitwise Operators
9. Logical Operators 10. Conditional Operator
11. Assignment Operator

3 - 14 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

19. Operator Precedence Table


Precedence Operators

Highest + - ! ~ ++x --x (T)x

*/ %

+-

<< >>

< > <= >= is as

== !=

&

&&

||

:?

Lowest = *= /= %= += -= <<= >>= &= ^= |=

20. Operator Associativity table


Operators Associativity

Primary Operators
., ->, ( ), [ ], ++ (as postfix), -- (as postfix), new, typeof, default, delegate, Left to Right
checked, unchecked

Unary Operators
Right to left
+ (unary), - (unary), !, ~, ++ (prefix), -- (prefix)

Multiplicative Operators
Left to Right
*, / and %

3 - 15 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Additive Operators
Left to Right
+ and -

Shift Operators
Left to Right
<<, >>

Relational and Type operators


Left to Right
<, <=, >, >=, is and as

Equality Operators
Left to Right
== and !=

Bitwise AND Operator


Left to Right
&

Bitwise XOR Operator


Left to Right
^

Bitwise OR Operator
Left to Right
|

Logical AND Operator


Left to Right
&&

Logical OR Operator
Left to Right
||

Conditional Operator
Right to Left
?:

Assignment Operator
Right to Left
= and any compound assignments (+=, -=, /=, *=,.......)

3.5 Expression

Concept

1. An expression is a sequence of one or more operands and zero or more operators that can
be evaluated to a single value, object, method, or namespace.

3 - 16 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Explanation

2. The most basic expression consists of an operator, two operands and an assignment. The
following is an example of an expression.
int sum = 10 + 20;
In the above example the (+) operator is used to add two operands (10 and 20 which are
constants).. The assignment operator (=) then assigns the result of the addition to an
integer variable named sum. The operands could just have easily been variables or
constants (or a mixture of each) instead of the actual numerical values.
3. Expressions can consist of a literal value, a method invocation, an operator and its
operands, or a simple name. Simple names can be the name of a variable, type member,
method parameter, namespace or type.
4. Expressions can use operators that in turn use other expressions as parameters, or method
calls whose parameters are in turn other method calls, so expressions can range from
simple to very complex.
Example

1. ((x < 20) && ( x > 15)) || ((x > 10) && (x < 50))
2. System.Convert.ToInt32("456")
5. In most of the contexts where expressions are used, the expression is expected to evaluate
to some value.
6. If num1 and num2 are integers, the expression num1 * num2 evaluates to a numeric value.
7. The expression evaluates to a reference to a new instance of a
NumberClass object.
8. The expression numberclass. evaluates to a string because that is the return
type of the method.
9. It should be noted that, although a namespace name is classified as an expression, it does
not evaluate to a value and therefore can never be the final result of any expression. One
cannot pass a namespace name to a method parameter, or use it in a new expression, or
assign it to a variable. One can only use it as a sub-expression in a larger expression. The
same is true for types (as distinct from System.Type objects), method group names (as
distinct from specific methods), and event add and remove accessors.
10. Every evaluated value has an associated type. For example, if num1 and num2 are both
variables of type the value of the expression num1 + num2 is also typed as int. If
this value is assigned to a variable of a different type, or if num1 and num2 are different
of types, the rules of Casting and Type Conversions are applied.

3 - 17 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

11. Overflows – Evaluation of numeric expressions may cause overflows if the value is
larger than the maximum value of the value's type.
12. Types of expression
12.1 Literals and Simple Names
Concept

The two simplest types of expressions are literals and simple names. A literal is a
constant value that has no name.
Example

In the above example, both num and msg are simple names that identify local
variables. When those variables are used in an expression, the variable name evaluates
to the value that is currently stored in the variable's location in memory. This is
illustrated below.
Example

12.2 Invocation Expressions


Concept

In the following code example, the call to method ReadFile is an invocation


expression.

Explanation

A method invocation requires the name of the method, either as a name as in the
previous example, or as the result of another expression, followed by parenthesis and
any method parameters.
A delegate invocation uses the name of a delegate and method parameters in
parenthesis.
Method invocations and delegate invocations evaluate to the return value of the
method, if the method returns a value.
Methods that return void cannot be used in place of a value in an expression.

3 - 18 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

12.3 Query Expressions


Concept

Language-Integrated Query (LINQ) is the name assigned for a set of technologies


based on the integration of query capabilities directly into the C# language
Explanation

LINQ is one of the greatest improvements to .NET. Because of introduction of


LINQ, a query is now a first-class language construct, just like classes, methods, events
and so on. For working with data in the database the query expressions are written in a
declarative query syntax jus like other declarative statements.
By using query syntax, complex filtering, ordering, and grouping operations on data
sources can be performed with a minimum of code. These basic query expression
patterns can also be used to query and transform data in SQL databases, ADO.NET
Datasets, XML documents and streams, and .NET collections.
Example

12.4 Lambda Expressions


Concept

Lambda expressions represent "inline methods" that have no name but can have input
parameters and multiple statements.
Explanation

They are used largely in LINQ to pass arguments to methods. Lambda expressions
are compiled to either delegates or expression trees depending on the context in which
they are used. Its syntax is,
(Input Parameters) => Method Expression
It’s a function without a name. But it has parameter and return value, but they are
dynamic, which means it can have any parameter for them.

3 - 19 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Example

The first part, before the ‘=>’ symbol, is refereed as the input parameter. It is not
required to define it previously. It is dynamic. The type of ‘num’ variable is decided
based on the operation performed on it.
12.5 Expression Trees
Concept

Expression trees enable expressions to be represented as data structures.


Explanation

Each node in an expression tree is an expression. For example, an expression tree can
be used to represent mathematical formula x < y where x, < and y will be represented as
an expression and arranged in the tree like structure.
They are used extensively by LINQ providers to translate query expressions into
code that is meaningful in some other context, such as a SQL database.
Expression tree is an in-memory representation of a lambda expression. It holds the
actual elements of the query, not the result of the query.
The expression tree makes the structure of the lambda expression transparent and
explicit. One can interact with the data in the expression tree just as one can with any
other data structure.
Example

Consider expression in C#,

Expression Tree in C# for above expression is as follows,

3.6 Checked and Unchecked Operator


Concept

two new features in C#


for developers These two operators force the CLR (Common Language Runtime) to handle

3 - 20 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

stack overflow situations. The checked operators enforces overflow through an exception if an
overflow occurs.
The unchecked operator does not
throw an exception if an overflow occurs.
Explanation
Checked Operator

When due to a limitation of a datatype, like an int, the data is lost or unpredictable value is
received, for skipping this garbage value and generate the "Stackoverflow exception" ,
checked operator is used. The checked keyword is used to control the overflow-checking
context for integral-type arithmetic operations and conversions. It can be used as an operator
or a statement according to the following forms.
The checked statement,
1. checked block
2. The statement block that contains the expressions to be evaluated in a checked context.
3. The checked operator.
4. checked (expression).
5. The expression to be evaluated in a checked context. Notice that the expression must be in
parentheses ( ).
The following operations are affected by the overflow checking :
Expressions using the following predefined operators on integral types :
++ — - (unary) + - * /
Explicit numeric conversions between integral types.
Unchecked Operator

It is the reverse of a checked operator where one get the garbage value in the actual
scenario. It is used by default in C#. If one want to suppress overflow checking, Unchecked
operator can be used. In this case, no exception will be raised, but data would be lost.
For example, the byte type can't hold a value of greater than 255. So the overflow bits will
be discarded and byte variable would hold a value of zero.
The unchecked statement can take up following forms,
1. unchecked block
2. The statement block that contains the expressions to be evaluated in an unchecked
context.
3. The unchecked operator.

3 - 21 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

4. unchecked (expression)
5. The expression to be evaluated in an unchecked context. Notice that the expression must
be in parentheses ( ).
Example

Two Marks Questions with Answers

Q.1 What does the tilde (~) mean in C# ?


Ans. : The ~ operator performs a bitwise complement operation on its operand, which has
the effect of reversing each bit. Bitwise complement operators are predefined for int, uint,
long, and ulong. Also the ~ symbol is used to declare destructors.
Q.2 What are types of operators based on number of operands ?
Ans. : Unary Operator : Operator that takes one operand to perform the operation.
Binary Operator : Operator that takes two operands to perform the operation.
Ternary Operator : Operator that takes three operands to perform the operation.
Q.3 What are Logical Operators in C# ?
Ans. : They are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. They are described below :
Logical AND : The '&&' operator returns true when both the conditions in
consideration are satisfied. Otherwise it returns false. For example, a && b returns true
when both a and b are true (i.e. non-zero).
Logical OR : The '||' operator returns true when one (or both) of the conditions in
consideration is satisfied. Otherwise it returns false. For example, a || b returns true if

3 - 22 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are
true.
Logical NOT : The '!' operator returns true the condition in consideration is not
satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when
a=0.
Q.4 What is bitwise 'and' and 'or' operators in C# ?
Ans. :
1. & (bitwise AND) Takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. | (bitwise OR) Takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 any of the two bits is 1.
Q.5 What is sizeof and typeof operator in C# ?
Ans. :

The sizeof() operator returns the size of a For example, sizeof(int), returns 4.
data type.
The typeof() operator returns the type of a For example,
class. typeof(StreamReader);
Q.6 List the operators that can be overloaded.
Ans. : Operators those can Overloaded in C#
Operators Overloading Possibilities

+, -, !, ~, ++, --, true, false These unary operators can be overloaded.

+, -, *, /, %, &, |, ^, <<, >> These binary operators can be overloaded.

==, !=, <, >, <=, >= The comparison operators can be overloaded.

&&, || The conditional logical operators cannot be overloaded,


but they are computed with & and |, which can be
overloaded.

Long Answered Questions

Q.1 Discuss various operators in C#. (Refer section 3.1)


Q.2 What is precedence and associativity ? (Refer section 3.4)
Q.3 What are checked and unchecked operators ? (Refer section 3.6)
Q.4 What is expression in C# ? (Refer section 3.5)
Q.5 Discuss various punctuations used in C#. (Refer section 3.3)

3 - 23 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Q.6 Explain in detail about the types of Operators. (Refer section 3.2)

Q.7 Describe the purpose of checked and unchecked operators. (Refer section 3.6)

Q.8 Given an array, write a C# program to right rotate it by k elements. Let the
elements be 1, 2, 3, 4, 5, 6, 7 8, 9, 10. If k = 3, after right rotation it becomes 8, 9,
10, 1, 2, 3, 4, 5, 6, 7.
Ans. :

3 - 24 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

Q.9 With examples explain the various arithmetic operators in C#.


(Refer section 3.2)

Core C# - Part II - Operators, Punctuations, Expressions ends …

3 - 25 C# and .NET Programming


Core C# - Part II - Operators, Punctuations, Expressions

3 - 26 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Flow Control.

Section No. Topic Name Page No.


4.1 Flow Control 4-2
4.2 Selection Statements 4-2
4.3 Iteration Statements 4 - 15
4.4 Jump Statements 4 - 24
4.5 Miscellaneous Statements 4 - 30
Two Marks Questions with Answers 4 - 33
Long Answered Questions 4 - 34

4-1 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

4.1 Flow Control

Concept

Control statements are used as additional means to control the processing within the
applications developed.
Explanation
Control Statements Description

Selection Statements A selection statement is a control statement that allows choosing


between two or more execution paths in a program on the basis of
some condition. These statements include if, else, switch, case.

Iteration Statements Iteration statements enable the user to perform the same set of
statements repeatedly until a specific condition is met. These
statements include for, while, do-while and for each loops.

Jump Statements Jump statements enable user to jump to another section of code on
the base of any condition or without any condition. These
statements include break, continue, goto, return and throw
statements.

Miscellaneous Statement Miscellaneous statements refer to specific statement used for


special purpose. These include block, empty, using statement.

4.2 Selection Statements

Concept

1. A selection statement is a control statement that allows for choosing between two or more
execution paths in a program on the basis of some condition.
Explanation

2. C# includes one-way, two-way and n-way (multiple) selectors.


2.1) An if statement with no else is a one way selector.
2.2) An if..else statement is a two way selector.
2.3) An if..elseif..else, nested if and switch statements are n-way selectors.

4-2 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

3. C# includes the following selection statements


1) If statement
2) If..else statement
3) If..elseif..else statement
4) Nested if statement
5) switch-case statement
6) nested switch-case statement
3.1. The if statement
Concept

1. It allows the user to execute different path of logic on the basis of a given condition.
Explanation

2. If statement is a most powerful decision making statement.


3. An if statement consists of a boolean expression followed by one or more statements.
4. If the condition is true the block of statements present in the body of if statement get
executed and if condition is false then other set of statement after if structure get
executed.
5. if statement Flowchart

Fig. 4.2.1 If statement

4-3 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

6. If statement Syntax

Example

Output

3.2 The if.. else statement


Concept

1. If..else statement contains the two blocks if block and else block.

4-4 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Explanation
2. An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
3. When condition present in parenthesis of if statement is true then statements of if block
are executed and if condition is false then statements of else block are executed.
4. if..else statement Flowchart

Fig. 4.2.2 if-else statement

5. if..else statement Syntax

Example

4-5 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

3.3. The if...elseif...else statement


Concept
1. It is always legal in C# to nest if-else statements, which means one can use if or else if
statement inside another if or else if statement(s).
Explanation
2. The if...elseif...else statement is very useful in the case where user want to select a option
from multiple options. In this type of statement 'if' is followed by one or more elseif
statements and finally end with a else statement.
3. The if...elseif...else statement Syntax

4-6 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Example

4-7 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

3.4 The Nested if statement


Concept
1. A nested if is an 'if' statement that is the target of another if or else statements.
Explanation
2. When ‘if’ statement is used to do nesting of , ‘if..else if..else’ or ‘if..else’ or statements
inside the other ‘if’ or ‘else if’ or ‘else’ statements that is known as nested if statements.
3. Nested if statement Flowchart

Fig. 4.2.3 Nested if statement

4-8 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

4. Nested if statement Syntax


Syntax

A nested if statement contains various structures like if..else statement inside if, if
statement inside else etc.
Example

4-9 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

3.5. The switch-case Statement


Concept

1. The switch case statement is used for selection from multiple expressions like
if..elseif..else statement but it is a better approach then if...elseif..if statement.
Explanation

2. Switch statement contains a expression in its parenthesis which can be a number, a


character or a string.
3. One switch statement is followed by several case statements.
4. The switch operator compares the expression to every value listed in the case labels in the
body of the switch structure. If a match is found in a case label, the corresponding
structure is executed (simple or complex). If no match is found, the default statement is
executed (if one exists).
5. Switch-Case statement Flowchart

4 - 10 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Fig. 4.2.4 Switch case statement

6. Switch-Case statement Syntax

4 - 11 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

7. Rules for switch-case statements


7.1. Expression present in parenthesis of switch statement must be char, byte, short, int,
enum or String. Floating point value cannot be a expression.
7.2. Case constant must be compatible to the expression of the switch statement.
7.3. No case constant in one switch can have an identical value.
7.4. When the expression is equal to a case label, the statements following that case
will execute until a break statement is reached.
7.5. Default is an optional statement which executed when expression does not match
with any case label.
Example

4 - 12 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

3.6. Nested switch-case statement


Concept

1. When switch-case statements are used inside another switch case statement that is known
as nested switch case statement.
Explanation

2. Nested switch-case statement syntax

4 - 13 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Example

4 - 14 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

4.3 Iteration Statements

Concept
1. Iteration statements enable the user to perform the same set of statements repeatedly until
a specific condition is met.
Explanation
2. Iteration statements also known as looping statements.
3. In C# there are following iteration or looping statements,
1) while loop 2) for loop 3) do-while loop
4) foreach loop 5) Nested Loop
4.3.1 While Loop
Concept
1. The while loop is a simple and most commonly used loop.
Explanation
2. While loop repeatedly executes a block of statements until specified condition get false.
3. While loop checks the condition before entering the first iteration.
4. While loop flowchart

Fig. 4.3.1 While loop

4 - 15 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

4. While loop syntax


Syntax

5. Body of while loop repeatedly executes as long as condition is true. When the condition
becomes false the program control shifts to the statements present just after the while
loop.
Example

Output

4 - 16 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

4.3.2 For Loop


Concept

1. The function of for loop is similar to the while loop the only difference is that its syntax is
different from the while loop which makes iteration on variable more handy .
Explanation

2. For loop repeatedly executes a block of statement until specified condition get false.
3. For loop is good for those situations where one exactly knows how many time one has to
execute the statements within the body of loop.
4. It also checks the condition before entering the first iteration.
5. For loop Flowchart

Fig. 4.3.2 For loop

4 - 17 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

6. For loop Syntax

7. Process of for loop


1) The first term in for loop is 'initialization' which allows the user to initialize the
value of loop counter and initialization is done first in the whole process of for
loop.
2) Next term is 'condition'. If the condition is true then only loop body gets executed
and if it is false the control of program is shifted to the statement just after the 'for'
loop.
3) Next term is 'increment/decrement' where the control goes after the execution of
the body the loop and loop counter gets updated either.
4) Steps 2 and 3 are repeated until the condition becomes false.
Example

Output

4 - 18 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

4.3.3 do-while Loop


Concept

1. do-while loop is iterative loop similar to the while loop but the difference is that it checks
the condition after the execution of the loop-body.
Explanation

2. do-while loop certainly execute once whether condition is true or false.


3. do-while loop Flowchart

Fig. 4.3.3 do-while loop

4. The do-while loop Syntax

4 - 19 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Example

Output

4.3.4 Foreach Loop


Concept

1. Foreach each loop is used to iterate the elements present in arrays and collections.

4 - 20 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Explanation

2. An array is a collection of the values of same data type.


3. Foreach loop is preferred where one wants to go through the all elements of an array.
4. Foreach loop Flowchart

Fig. 4.3.4 For each loop

5. Foreach loop Syntax

6. In the above syntax statement, type variable shows the iterative elements and expression
is the name of array.

4 - 21 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Example

using System;

Output

4.3.5 Nested Loop


Concept

1. When one loop is used inside the other loop that is known as nested loop.
Explanation

2. One can use for loop inside while loop, do-while loop inside for loop, while loop inside
while loop or so on.

4 - 22 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

3. Nested loop Flowchart

Fig. 4.3.5 Nested loop

4. Nested loop Syntax

5. Nested loop can have various structures based on which loop is being nested inside
another loop.
Example

4 - 23 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

4.4 Jump Statements

Concept

1. Jump statement enables user to jump to another section of code either conditionally or
unconditionally.

4 - 24 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Explanation

2. Jump statement is basically used for the branching which causes the immediate transfer of
the control of program to the other section of code.
3. These statements are also used where one need to interrupt any loop or switch-case
statement in between the on processing.
4. There are five kinds of Jump statements present in the C# which are as follows,
1. break 2. continue 3. goto 4. return 5. throw
5. In this section the break, continue and goto statements would be discussed. Return
statement would be discussed in C# methods section and throw statement would be
discussed in the C# Exception Handling section.
4.4.1 The Break Statement
Concept

1. The break statement terminates the enclosing loop or switch case statements and
program's control jump to the statement immediately following the loop or switch-case
statement.
Explanation

2. Break statement flowchart

Fig. 4.4.1 Break statement

2. Break statement syntax

4 - 25 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Example

Output

4.4.2 The Continue Statement


Concept

1. The continue statement forces the program control to go directly to the condition and then
continue the next iteration.
Explanation

2. Continue statement stops the current iteration and starts the next iteration.
3. Continue statement flowchart

4 - 26 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Fig. 4.4.2 Continue statement

4. Continue statement syntax

Example

4 - 27 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Output

4.4.3 The goto Statement


Cocnept

1. The goto statement is used to jump to the specific section of code followed by a
predefined label.
Explanation

2. The goto statement is most often used when there is a critical situation and there is no as
such a conditional path to get outside the loop.
3. It is widely used in nested loops.
4. The goto statement flowchart

Fig. 4.4.3 goto statement

5. The goto statement syntax

4 - 28 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Example

Output

4 - 29 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

4.5 Miscellaneous Statements

4.5.1 Block Statement


Concept

1. The block statement is used to group multiple segments of program which are logical
related.
Explanation

2. Block statement syntax

Example

Ouput

4.5.2 Empty Statements


Concept

1. Empty statement is used when there is no need to perform an operation where generally a
statement is required.
Explanation

2. It simply transfers control to the end point of the statement.

4 - 30 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

3. It is handy with while loop having blank body and label statements.
4. Empty statement syntax

Example

Output

4.5.3 The Using statement


Concept

1. The using statement is used to add one or more resources in a program.


Explanation

2. The using statement obtains one or various resources, executes them and then releases the
objects or resources.

4 - 31 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

3. Using statement is used in every C# program for adding required built-in collection of
namespaces and classes. It is widely used in database connectivity through C#.
4. Using statement syntax

Example

Output

4 - 32 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Two Marks Questions with Answers

Q.1 If you want to replace multiple if-else statements in code, which statement will
you use ?
Ans. : In Visual basic, we can use Select-Case statement to replace multiple If-Else
statement. In C#, we should use Switch-Case statement to replace multiple If-Else
statement.
Q.2 What are two different ways to implement multi selections in C# language ?
Ans. : If-else and switch are two ways to implement multi selections in C#.
Q.3 Give the output of the following.
Ans. :

In above program else block is executed. Since i is defined globally, it is initialized with
default value 0. The Else block is executed as the expression within if evaluates to FALSE.
Please note that the empty block is equivalent to a semi-colon(;). So the statements if (i);
and if (i) {} are equivalent.
Q.4 How many times will ‘C# - is too sharp’ be printed in the below program ?
Ans. :

Above program will print the statement 11 times. In for loop, mentioning expression is
optional.

4 - 33 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

>>= is a composite operator. It shifts the binary representation of the value by 1 to the
right and assigns the resulting value to the same variable. The for loop is executed until
value of variable i doesn’t drop to 0.
Q.5 What is the output of following program ?
Ans. :

Program outputs ‘Love’. The given expression gets evaluated in cases. The control goes
to the second case block after evaluating 1 + 2 = 3.

Long Answered Questions

Q.1 What is a control statement ? (Refer section 4.1)


Q.2 Discuss various condition checking statements provided by C#.
(Refer section 4.1)
Q.3 What is use of break and continue ? (Refer section 4.4)
Q.4 What is necessary for any looping statement ? (Refer section 4.3)
Q.5 What is the purpose of using statement ? (Refer section 4.5)
Q.6 Write a C# program to check whether the entered year is a Leap year or not.

Ans. :

4 - 34 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Q.7 Write a C# program to Get a Number and Display the Number in its Reverse
order.
Ans. :

Q.8 Write a C# program to Sort a List of Names in Alphabetical Order.

Ans. :

4 - 35 C# and .NET Programming


Core C# - Part III - Flow Control and Various Control Statements

Core C# - Part III - Flow Control and Various Control Statements ends …

4 - 36 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Core C#.

Section Topic Name Page No.


No.
5.1 Methods 5-2
5.2 Static Methods 5 - 13
5.3 Instance Methods 5 - 14
5.4 Anonymous Methods 5 - 15
5.5 Method Overloading 5 - 16
5.6 Hiding Methods, Overriding Methods and Sealed Methods 5 - 16
5.7 Unsafe Method or Unsafe Block 5 - 16
Two Marks Questions with Answers 5 - 18
Long Answered Questions 5 - 20

5-1 C# and .NET Programming


Core C# - Part IV - Functions and Methods

5.1 Methods

Concept

1. A method is a group/block of statements that together perform a task.


Explanation

2. When class is created, the fields are meant to describe the properties of the class. Besides
the characteristics used to describe it, an object can perform actions or assignments and
manipulations.
3. An action performed by a class is called a function or a method.
4. A method allows to encapsulate a piece of code and call it from other parts of the code. A
method is simply a section of code in which particular detail for the functionality of the
class is written.
5. One can create as many methods as required in a class.
6. Every C# program has at least one class with a method named Main.
7. For using method one needs to,
Define the method and then
Call the method
7.1 Defining Method in C#
1. By defining a method, it means to declare the elements of its structure.
2. Syntax for defining a method in C#

Where,
Access Specifier is, determines the visibility of a variable or a method from
another class. The visibility is optional. If not specified then the method would be
private.
If the method is to be accessed only by members of the same class, it is marked as
private or left without an access modifier.
If the method is to be accessed by members of the class and other parts of the
same program but not outside of the program, it is marked with the internal
keyword

5-2 C# and .NET Programming


Core C# - Part IV - Functions and Methods

If the method is to be accessed by the members of the same class, other parts of the
same program, and other parts of other programs, it is marked as public
Return type is, the data type of the value the method returns. A method may return a
value. If the method is not returning any values, then the return type is void.
A method can also return an expression, provided the expression produces a value that
is conform to the return type. Here is an example:

Method name is, a unique identifier and it is case sensitive. It cannot be same as any
other identifier declared in the class.
Parameter list is, enclosed between parentheses and the parameters are used to pass
and receive data from a method. The parameter list refers to the type, order, and number
of the parameters of a method. Parameters are optional; that is, a method may contain no
parameters.
Method body contains, the set of instructions needed to complete the required activity.
Example

5-3 C# and .NET Programming


Core C# - Part IV - Functions and Methods

7.2 Calling Method in C#


1. A method is called using the name of the method as shown below.
2. Public method can be called from other classes by using the instance of the class to
which method belongs.
Example

Output

Example

5-4 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Output

7.3 Passing Parameters to a Method


Concept

1. There are three ways that parameters can be passed to a method while calling the
method.
Explanation

2. These three methods are as follows.


2.1 Passing parameters by value - 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.

5-5 C# and .NET Programming


Core C# - Part IV - Functions and Methods

The following statement is used to define the syntax to declare a value parameter.

2.2 Passing parameters by reference - 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.
A reference parameter is the reference to the memory location of a parameter. In
reference parameter new storage location is not created. It stores the value in the
same memory location as the variable passed is in the memory call.
The declaration of the reference parameter is done by using the ref keyword. The
example for the reference parameters is as shown below,

2.3 Passing parameters using output parameters - In this method more than one
value can be returned to the calling method.
A return statement is used for returning a value from the method. A return statement
can be used to return only a single value. The output parameter is used to overcome
this problem.
Output parameters are like reference parameters but they transfer data out of the
method. An output parameter is reference to the storage location supplied by the
caller. To declare an output parameter, the out keyword is used before the data type
and the variable name.
Out parameter are specified as shown below,
static void Outsample( out int i )

2.4 Variable number of arguments to the method - A method can take variable
number of arguments. For this the params keyword is used. No additional
parameters are permitted after the params keyword.
Only one params keyword is permitted in a method declaration.

5-6 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Example

Output

7.4 Recursive Method Call


Concept

1. A method can call itself. This is known as recursion.

5-7 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Explanation
2. Recursion, in mathematics and computer science, is a way of defining methods in which
the method being defined is applied within its own definition.
3. In other words, a recursive method calls itself to do its job.
4. Recursion is a widely used approach to solve many programming tasks.
Example

When the above code is compiled and executed, it produces the following result :

5-8 C# and .NET Programming


Core C# - Part IV - Functions and Methods

7.5 Naming the method (Nomenclature for method)


7.5.1. The name of a method primarily follows the rules defined for names of variables.
Refer (Chapter 2 - section 2.6)
7.5.2. Besides those rules, following are some suggestions for naming the methods.
2.1 If the name of a method is in one word, the first letter will be in uppercase
2.2 If the name of a method is a combination of words, the first letter of each word
will be in uppercase
2.3 Because a method is an action, generally method name should be a verb.
7.5.3 The method names are verbs or verbs followed by adjectives or nouns. Each subsequent
word starts with an uppercase character. The following are typical names of methods in
C#:
Execute
FindRollNo
SetName
GetName
CheckIfValid

8. The Main - Main method (public static void Main(String[] args))


8.1 There is at least one method inside C# class which is main where the execution of
program starts. It is the main entry point of program that executes all the objects and
invokes method to execute. There can be only one Main method in C#.
8.2 Default implementation of the Main() method is of type void. Another way to
implement the Main() method is to make it return an integer. The rule is the same as
for any method of type int. The Main() function can return any type of integer as
long as it is a valid integer.
8.3 The Main method in C# is always declared as static because it has to be called
before creation of any object or before calling any other method in the program. The
Main method instantiate other objects and variables but there is no method that can
instantiate main method in C#. On other hand, the main method doesn’t accept
parameter from any other method. It only takes parameter as argument via
command line argument.
8.4 The Main method can have a parameter and these parameters are known as zero-
indexed command line argument.

5-9 C# and .NET Programming


Core C# - Part IV - Functions and Methods

9. Method scope
Concept

1. A variable declared inside a method has a method scope.


Explanation

2. The scope of a name is the region of program text within which it is possible to refer to
the entity declared by the name without the qualification of the name.
3. A variable which is declared inside a method has a method scope. It is also called a local
scope.
4. The variable is valid only in this particular method.
Example

5 - 10 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Output

5. A variable defined inside a method has a local/method scope. If a local variable has the
same name as an instance variable, it shadows the instance variable. The class variable is
still accessible inside the method by using the ‘this’ keyword.
Example

In the preceding example, variable n is declared twice, outside the exec() method and
inside the exec() method. Both variables have the same name, but they do not conflict because
they live in different scopes.

5 - 11 C# and .NET Programming


Core C# - Part IV - Functions and Methods

The variables are accessed differently. The variable n defined inside the method, also
called the local variable, is simply accessed by its name. The instance variable can be referred
by using the this keyword.

Output

10. this reference


10.1 The this keyword is used to refer to the current instance of the class.
10.2 It can be used to access members from within the constructors and instance
methods.
10.3 The naming conflicts can be eliminated using this reference. They cannot be
used as reference to a static field or method. They cannot be part of static class.

Output

5 - 12 C# and .NET Programming


Core C# - Part IV - Functions and Methods

11. Advantages of using Method


1. Reduction duplication of code.
2. Decomposing complex problems into simpler pieces that bring modularity to
programs.
3. Improving clarity of the code.
4. Reuse of code.
5. Information hiding.
6. Isolation of code that helps in ease of error tracing and debugging.

5.2 Static Methods

Concept

1. Static methods are invoked directly from the class level without creating an object. Static
methods are called without an instance of the object.
Explanation

2. Static methods do not have instances. They are called with type name, not by identifier.
They can be public or private. To call a static method, use the name of the class and the
dot operator.
3. Static methods can only work with static member variables.
4. Static methods are often used to represent data or calculations that do not change in
response to object state. An example is a math library which contains static methods for
various calculations.
5. Keyword ‘static’ is used to declare a static method. When no static modifier is present, the
method is said to be an instance method.
6. One cannot use the this keyword in static methods. It can be used in instance methods
only.
8. The Main() method is an entry point to the C# console and GUI application. In C#, the
Main() method is required to be static. Before the application starts, no object is created
yet.
9. To invoke non-static methods, one need to have an object instance. Static methods exist
before a class is instantiated so static is applied to the main entry point.

5 - 13 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Example

Output

5.3 Instance Methods

Concept

1. The instance methods in a class make use of public or private or static data that belongs to
the class.
Explanation

2. User can access methods using the object of the class. Add the method name preceding
the dot operator in the declaration.

5 - 14 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Example

Output

5.4 Anonymous Methods

Concept

1. Anonymous methods are inline methods that do not have a name.


Explanation

2. Anonymous methods reduce the coding overhead by eliminating the need to create a
separate method.
3. Without anonymous methods developers often had to create instance of a class just to call
one method.
Example

5 - 15 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Output

5.5 Method Overloading

This concept would be studied in Chapter - 8. Refer section 8.2.

5.6 Hiding Methods, Overriding Methods and Sealed Methods

These concepts would be studied in Chapter - 8 and Chapter - 9.


Refer section 8.1 for sealed method.
Refer section 9.3 for overriding.
Refer section 9.4 for method hiding.

5.7 Unsafe Method or Unsafe Block

1. Unsafe code is code in which pointer manipulations have been done.


2. Advantages of unsafe code in C#
1. Performance and flexibility enhances because, by using pointer data can be accessed
and manipulated in the most efficient way possible.
2. Compatibility is the major reason for using pointers as old windows APIs used the
pointers extensively. Many third parties DLLs may supply their functionality

5 - 16 C# and .NET Programming


Core C# - Part IV - Functions and Methods

through pointer parameters. (Though pointers can be avoided in DLL usage by


writing the DLLimport declaration.)
3. If there is need of memory addresses access, then there is no way to know the
memory address of some data without using pointers.
3. Disadvantages of unsafe code in C#
1. Pointers have complex syntax.
2. Logically pointers are harder to use. If not used in proper way or steps it may lead to
miserable situation such as,
Overwrite other variables.
Stack overflow.
Access areas of memory that doesn’t contain any data as they do.
Overwrite some information of the code for the .net runtime, which will surely
lead application to crash.
3. It is hard to debug the code containing pointers as it can crash abruptly.
4. .net supports type-safety, which is harmed by using pointers. This may result in
non-execution of code as well.
4. Characteristics of unsafe code
1. Methods, types, and code blocks can be defined as unsafe.
2. In certain cases, unsafe code may increase an application's performance by
removing array bounds checks.
3. Unsafe code is required when native functions are called that require pointers.
4. For C# to compile unsafe code, the application must be compiled with /unsafe.
Example

5 - 17 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Two Marks Questions with Answers

Q.1 What is the difference between public, static, and void ?


Ans. : Public declared variables or methods are accessible anywhere in the application.
Static declared variables or methods are globally accessible without creating an instance of
the class. Static member are by default not globally accessible it depends upon the type of
access modified used. The compiler stores the address of the method as the entry point and
uses this information to begin execution before any objects are created. And Void is a type
modifier that states that the method or variable does not return any value.
Q.2 What is an Inline function ?
Ans. : An inline function is a technique used by the compilers and instructs to insert
complete body of the function wherever that function is used in the program source code.
Q.3 What is the main difference between overloading and overriding ?
Ans. : Overloading is static Binding, whereas Overriding is dynamic Binding. Overloading
is nothing but the same method with different arguments, and it may or may not return the
equal value in the same class itself.

5 - 18 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Overriding is the same method names with the same arguments and return types
associated with the class and its child class.
Q.4 What are the access modifiers ?
Ans. : Access modifiers determine the scope of the method or variables that can be
accessed from other various objects or classes. There are five types of access modifiers,
and they are as follows :
Private
Protected
Public
Friend
Protected Friend
Q.5 Can you return multiple values from a function in C# ?
Ans. : Multiple values can be returned from functions in C# using output parameters. A
return statement can be used for returning only one value from a function. However, using
output parameters, you can return two values from a function.
Q.6 Write a C# program to find the length of the Jagged Array using predefined
functions.
Ans. :

5 - 19 C# and .NET Programming


Core C# - Part IV - Functions and Methods

Long Answered Questions

Q.1 What are static methods in C# ? (Refer section 5.2)


Q.2 Discuss anonymous methods in C#. (Refer section 5.4)
Q.3 Write a note on 'Method Overriding'. (Refer section 5.6)
Q.4 Discuss method hiding. (Refer section 5.1)
Q.5 What are sealed methods in C# ? (Refer section 5.6)
Q.6 Differentiate static and non-static members of a class.
Ans. : A static method belongs to the class and a non-static method belongs to an object of
a class. The static methods can by accessed directly from the class, while non-static
methods (or instance methods) have to be accessed from an instance.
A static method is shared by all instances of the class. Whenever a method is called in
C++/Java/C#, an implicit argument "this" reference is passed along with/without the
other parameters. In case of a static method call, the "this" reference is not passed as
static methods belong to a class and hence do not have the "this" reference.
A non-static method can only be called on an object of a class that it belongs to. A
static method can access only static members. A non-static method can access both
static and non-static members because at the time when the static method is called, the
class might not be instantiated (if it is called on the class itself). In the other case, a
non-static method can only be called when the class has already been instantiated.
The objects of the class can not have the copy of these fields. These fields are referred
by the class name. Ex : Employee. company. Without creating an instance of a class,
these fields can be accessed.
The Static and Non-static variables in C# - Whenever a variable is declared by
using the static modifier or when variable is declared inside any static block then those
variables are considered as static variables whereas the rest of the other are considered
as non-static variables.
If one wants a variable to have the same value throughout all instances of a class then
it is needed to declare that variable as a static variable. So, the static variables are
going to hold the application level data which is going to be the same for all the
objects.
A non-static field is accessed by all objects of the class. Each object has one copy of
non-static field. To use non static fields, an instance of the class should be created.
Static and Non-Static Constructor in C# - If the constructor is written explicitly by
the static modifier, then it is called as static constructor and the rest of the others are

5 - 20 C# and .NET Programming


Core C# - Part IV - Functions and Methods

the non-static constructors. The most important point that one needs to remember is
the static constructor is the fast block of code which gets executes under a class. No
matter how many numbers of objects created for the class the static constructor is
executed only once. On the other hand, a non-static constructor gets executed only
when the object of the class is created and that is too for each and every object of the
class.
It is not possible to create a static constructor with parameters. This is because the
static constructor is the first block of code which is going to execute under a class.
And this static constructor called implicitly, even if parameterized there is no chance
of sending the parameter values.
Understanding the Static class in C# - The class which is created by using the static
modifier is called a static class. A static class can contain only static members in it. It
is not possible to create an instance of a static class. This is because it contains only
static members those can be accessed by the other static members of a class by using
the class name.
Q.7 Explain virtual methods and overriding. (Refer section 5.6)

Core C# - Part IV - Functions and Methods ends …

5 - 21 C# and .NET Programming


Core C# - Part IV - Functions and Methods

5 - 22 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Arrays and Tuples.

Section No. Topic Name Page No.


6.1 C# Arrays 6-2
6.2 Array Class 6 - 12
6.3 ArrayList Class 6 - 18
6.4 String Class 6 - 20
6.5 StringBuilder Class 6 - 26
6.6 Tuple 6 - 28
Two Marks Questions with Answers 6 - 33
Long Answered Questions 6 - 35

6-1 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

6.1 C# Arrays

6.1.1 Concept

Array is a collection of the data elements or values of same data type.


Explanation
1. In C# array is a reference type.
2. Each array in C# is an object.
3. Each array is inherited from the class System.Array.
4. The individual values present in an array are called as array elements.
5. Individual array element is accessed using the name of array and the index number
representing the position of element in an array.
6. Memory allocation of array - Array consists of the contiguous memory locations. Lower
address memory location represents first element and highest address memory location
represents last element. This is depicted in the following figure.

Fig. 6.1.1 Arrays

7. Using arrays
7.1 Declaration of array

datatype can be any primitive or refrence data type like int, float, string etc.
[] represents the size of the array.
arrayname is the name given to the array.
Array declaration examples

6-2 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

7.2 Creation of an array


Only declaration of an array is not sufficient to use arrays. One needs to create the
array for using the array in the program.
For creating an array ‘new’ keyword is used using which actual memory is allocated
for array elements.
Array creation syntax

Size here represents the size of an array.


Array creation examples

7.3 Initialization and Assigning value to the elements of array


Before using array one needs to assign values to the elements of an array.
Value can be assigned to the array element by using its index number.

Value can be assigned to the elements of array at the time of declaration or creation of
array.

7.4 Traversing and Accessing element stored in array


Array elements are accessed by writing the name of array with the index of the
element to be accessed, in the square bracket.
By default the array index value in C# starts from 0.
To access the value stored in the second element of the array named days (which is
stored at index value 1), following statements is used,

6-3 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Here, "Tuesday" will be stored in the string type variable 'today'.


Example

Output

7.5 Accessing array elements using for each loop


foreach looping statement can be used to iterate through an array.
Example

6-4 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

6.1.2 Types of Array


6.1.2.1 Concept

In C# there are four types of array as explained below.


Types of arrays Description
One Dimensional Array A simple array which contains only one dimension known as one
dimensional array.
MultiDimensional Array Array which contains more than one dimension is known as
MultiDimensional Array. Simplest form of multidimensional array
is ‘two-dimensional array’.

6-5 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Jagged Array Jagged array is “array of array”.


Param Array Param array is used to passing unknown number of parameter to a
method

6.1.2.2 One Dimensional Array

Concept

An array which contains only one dimension ( 1 row) is known as one dimensional array.
Explanation

1 Dimensional array declaration

6.1.2.3 Multidimensional Array

Concept

An array which contains more than one dimension (multiple rows and columns) is known
as Multidimensional array.
Explanation

1. For programming, two-dimensional array is widely used which is the simplest form of the
multi dimensional array.
2. Multidimensional array declaration

3. Example

4. Two-dimensional array
Concept

Two-dimensional array is a simplest form of the multidimensional array. Which has two
dimensions ( interpreted as 1 row and 1 column) is known as two-dimensional array.
Explanation

1. Two-dimensional array can be thought of as matrix. A matrix has rows and columns as its
dimension.
2. If a two-dimensional array has size m rows by n columns then there are total (m*n)
elements in the array.

6-6 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

3. Following is two-dimensional array of size (4*3) means a matrix of 4 rows and 3 columns
each whose elements are represented as follows,
Column0 Column1 Column2 Column3

Arr[0] [0]=1 Arr[0] [1]=4 Arr[0] [2]=9 Arr[0] [3]=5 Row0

Arr[1] [0]=4 Arr[1] [1]=4 Arr[1] [2]=1 Arr[1] [3]=2 Row1

Arr[2] [0]=6 Arr[2] [1]=3 Arr[2] [2]=7 Arr[2] [3] Row2

4. Each element in the two dimensional array is represented as arrayname[rowno][colno].


Here rowno and colno shows the value of row and column respectively.
5. Initialization of two-dimensional array :
Two-dimensional array is initialized in the same way as one dimensional array as
shown below.

6. Accessing the element of two dimensional array :


Two-dimensional array elements can be accessed by using the array name with its two
index-numbers, row index and column index as shown below.
Element stored at position, row 2 column 3, is accessed as
matrix[1, 2]
Example

6-7 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

6.1.2.4 Jagged Array

Concept
1. In C#, a Jagged array is an array of array in which each row of jagged array contains its
own array and the length of each array can be different.
Explanation

2. Jagged array declaration

In above example the jaggedArray has 3 arrays in it, with first array having 4 elements,
second array having 2 elements and third array 5 elements.
3. Jagged array initialization
Before using the jagged array it has to be initialized as given below,

6-8 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

4. Accessing the element of jagged array


Element of a jagged array are accessed using array name and its index as shown below.

Example

6-9 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

6.1.2.5 Param Array

Concept

While dealing with the method when it is not sure about the number of parameters of the
method then Param array can be is used effectively.
Explanation

Param array is used to pass unknown number of parameter to a method.


Example

6 - 10 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

6.1.3 Passing Array as Parameter


Concept

Array can be passed to a method just like other parameters in C#.


Example

6 - 11 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

6.2 Array Class

Concept

In C# array is treated as object and inherited from the Array class. Array class is defined in
the System namespace.
Explanation

1. Various properties of the Array class are listed below.


Properties Description Basic syntax

Length Return the Length of an array. It returns 32- Arrayname.Length


bit Integer value.

LongLength Return the Length of an array. It return 64- Arrayname.LongLength


bit integer value.

Rank Return the rank or number of dimension of Arrayname.Rank


an array. It returns integer value.

IsFixedSize Check whether the array is of fixed size or Arrayname.IsFixedSize


not. It returns Boolean value.

IsReadOnly Check whether the array is Readonly or not. Arrayname, IsReadOnly


It return Boolean value.

Example

6 - 12 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

2. Array Class methods


Commonly used methods of an array class are given below in the table.
ArrayClass Methods Description

Clear Sets a range of elements in the Array to zero, to false, or to Nothing,


depending on the element type.

6 - 13 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Copy Copies a range of elements from on Array starting at the first


element and paste them into another Array starting at the first
element.

GetLength Gets the number of elements present in an array.

GetLowerBound Gets the lower bound of the specified dimension in the Array.

GetUpperBound Gets the upper bound of the specified dimension in the Array.

IndexOf Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.

Reverse Reverses the sequence of elements of an array.

Sort Sorts an array.

Example

6 - 14 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

6 - 15 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

3. Using GetValue and SetValue methods of class Array


The GetValue and SetValue methods of the Array class can be used to get and set
values of an array's elements.
Example

6 - 16 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Output

4. Clonning an Array
Clone method creates a shallow copy of an array.
A shallow copy of an array copies only the elements of the array, whether they are
reference types or value types, but it does not copy the objects that the references refer
to.
The references in the new array point to the same objects that the references in the
original array point to.
Syntax for using Clone method

6 - 17 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

6.3 ArrayList Class

Concept

It represents an ordered collection of an object that can be indexed individually.


Explanation

1. It is used as an alternative to an array. Unlike array item can not be added or removed
from a list at a specified position using an index and the array resizes itself automatically.
2. This collection dynamically resizes. It grows in capacity as elements are added (if space is
needed). It holds objects. It stores elements of type object-casting is needed.
3. It supports operation like, adding, searching and sorting items in the list.
4. Properties of ArrayList Class
Commonly used properties of the ArrayList class are,

Property Description

Capacity Gets or sets the number of elements that ArrayList may contain.

Count Gets the number of elements actually contained in ArrayList.

IsFixedSize Gets a boolean value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a boolean value indicating whether the ArrayList is read-only.

Item Gets or sets the element at the specified index.

5. Methods of ArrayList class


Commonly used methods of the ArrayList class are,
Methods

1. public virtual int Add(object value);


Adds an object to the end of the ArrayList.
2. public virtual void AddRange(ICollection c);
Adds the elements of an ICollection to the end of the ArrayList.
3. public virtual void Clear();
Removes all elements from the ArrayList.
4. public virtual bool Contains(object item);
Determines whether an element is in the ArrayList.

6 - 18 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

5. public virtual ArrayList GetRange(int index, int count);


Returns an ArrayList which represents a subset of the elements in the source ArrayList.
6. public virtual int IndexOf(object);
Returns the zero-based index of the first occurrence of a value in the ArrayList or in a
portion of it.
7. public virtual void Insert(int index, object value);
Inserts an element into the ArrayList at the specified index.
8. public virtual void InsertRange(int index, ICollection c);
Inserts the elements of a collection into the ArrayList at the specified index.
9. public virtual void Remove(object obj);
Removes the first occurrence of a specific object from the ArrayList.
10. public virtual void RemoveAt(int index);
Removes the element at the specified index of the ArrayList.
11. public virtual void RemoveRange(int index, int count);
Removes a range of elements from the ArrayList.
12. public virtual void Reverse();
Reverses the order of the elements in the ArrayList.
13. public virtual void SetRange(int index, ICollection c);
Copies the elements of a collection over a range of elements in the ArrayList.
14. public virtual void Sort();
Sorts the elements in the ArrayList.
15. public virtual void TrimToSize();
Sets the capacity to the actual number of elements in the ArrayList.
Example

6 - 19 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

When the above code is compiled and executed, it produces the following result :

6.4 String Class

Concept

The String class in C# represents a string which holds collection of characters or text as a
series of Unicode characters.

6 - 20 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Explanation

1. The Char data type represents a character in C#. In C#, text is stored as a sequential read-
only collection of Char objects. There is no null-terminating character at the end of a C#
string; therefore a C# string can contain any number of embedded null characters ('\0').
2. The System.String data type is used to represent a string in .NET. A string in C# is an
object of type System.String.
3. Creating a String Object - String object can be created using one of the following
methods,
By assigning a string literal to a String variable.
By using a String class constructor.
By using the string concatenation operator (+).
By retrieving a property or calling a method that returns a string.
By calling a formatting method to convert a value or an object to its string
representation.
4. Properties of the String class
Chars

Gets the Char object at a specified position in the current String object.
Length

Gets the number of characters in the current String object.


5. Methods of the String class
The String class has numerous methods that help in working with the string objects, some
of the commonly used methods are as follows,
Methods

1. public static int Compare(string strA, string strB)


Compares two specified string objects and returns an integer that indicates their relative
position in the sort order.

2. public static int Compare(string strA, string strB, bool ignoreCase )


Compares two specified string objects and returns an integer that indicates their relative
position in the sort order. However, it ignores case if the Boolean parameter is true.

3. public static string Concat(string str0, string str1)


Concatenates two string objects.

6 - 21 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

4. public static string Concat(string str0, string str1, string str2)


Concatenates three string objects.
5. public static string Concat(string str0, string str1, string str2, string str3)
Concatenates four string objects.
6. public bool Contains(string value)
Returns a value indicating whether the specified String object occurs within this string.
7. public static string Copy(string str)
Creates a new String object with the same value as the specified string.
8. public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
Copies a specified number of characters from a specified position of the String object to a
specified position in an array of Unicode characters.
9. public bool EndsWith(string value)
Determines whether the end of the string object matches the specified string.
10. public bool Equals(string value)
Determines whether the current String object and the specified String object have the same
value.
11. public static bool Equals(string a, string b)
Determines whether two specified String objects have the same value.
12. public static string Format(string format, Object arg0)
Replaces one or more format items in a specified string with the string representation of a
specified object.
13. public int IndexOf(char value)
Returns the zero-based index of the first occurrence of the specified Unicode character in the
current string.
14. public int IndexOf(string value)
Returns the zero-based index of the first occurrence of the specified string in this instance.
15. public int IndexOf(char value, int startIndex)
Returns the zero-based index of the first occurrence of the specified Unicode character in this
string, starting search at the specified character position.
16. public int IndexOf(string value, int startIndex)
Returns the zero-based index of the first occurrence of the specified string in this instance,
starting search at the specified character position.

6 - 22 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

17. public int IndexOfAny(char[] anyOf)


Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters.
18. public int IndexOfAny(char[] anyOf, int startIndex)
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters, starting search at the specified character position.
19. public string Insert(int startIndex, string value)
Returns a new string in which a specified string is inserted at a specified index position in the
current string object.
20. public static bool IsNullOrEmpty(string value)
Indicates whether the specified string is null or an Empty string.
21. public static string Join(string separator, params string[] value)
Concatenates all the elements of a string array, using the specified separator between each
element.
22. public static string Join(string separator, string[] value, int startIndex, int count)
Concatenates the specified elements of a string array, using the specified separator between
each element.
23. public int LastIndexOf(char value)
Returns the zero-based index position of the last occurrence of the specified Unicode character
within the current string object.
24. public int LastIndexOf(string value)
Returns the zero-based index position of the last occurrence of a specified string within the
current string object.
25. public string Remove(int startIndex)
Removes all the characters in the current instance, beginning at a specified position and
continuing through the last position, and returns the string.
26. public string Remove(int startIndex, int count)
Removes the specified number of characters in the current string beginning at a specified
position and returns the string.
27. public string Replace(char oldChar, char newChar)
Replaces all occurrences of a specified Unicode character in the current string object with the
specified Unicode character and returns the new string.
28. public string Replace(string oldValue, string newValue)
Replaces all occurrences of a specified string in the current string object with the specified
string and returns the new string.

6 - 23 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

29. public string[] Split(params char[] separator)


Returns a string array that contains the substrings in the current string object, delimited by
elements of a specified Unicode character array.
30. public string[] Split(char[] separator, int count)
Returns a string array that contains the substrings in the current string object, delimited by
elements of a specified Unicode character array. The int parameter specifies the maximum
number of substrings to return.
31. public bool StartsWith(string value)
Determines whether the beginning of this string instance matches the specified string.
32. public char[] ToCharArray()
Returns a Unicode character array with all the characters in the current string object.
33. public char[] ToCharArray(int startIndex, int length)
Returns a Unicode character array with all the characters in the current string object, starting
from the specified index and up to the specified length.
34. public string ToLower()
Returns a copy of this string converted to lowercase.
35. public string ToUpper()
Returns a copy of this string converted to uppercase.
36. public string Trim()
Removes all leading and trailing white-space characters from the current String object.
Note : Visit MSDN library for the complete list of methods and String class constructors.
6. Empty string - An empty string is a valid instance of a System.String object that contains
zero characters. There are two ways to create an empty string. One can either use the
string.Empty property or can simply assign a text value with no text in it.
The following code snippet creates two empty strings.

Both of the statements above generates the same output.


7. Null string - A null string is a string variable that has not been initialized yet and has a
null value. If one tries to call any methods or properties of a null string, one will get an
exception. A null string variable is exactly same as any other variable defined in the code.
A null string is typically used in string concatenation and comparison operations with
other strings.

6 - 24 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

The following code example shows how to use a null string.

Example

6 - 25 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

When the above code is compiled and executed, it produces the following result :

6.5 StringBuilder Class


Concept

A StringBuilder object is not a string but rather an auxiliary object used for manipulating
characters.
Explanation

1. StringBuilder contains a buffer, typically initialized with a string but usually larger than
that string. This buffer can be manipulated in place without creating a new string.
2. One can insert, append, remove, and replace characters. When manipulations are done
StringBuilder's, ToString method, is used to extract the finished string from it.
3. StringBuilder is mutable, means if string builder object is created then one can perform
any operation like insert, replace or append without creating new instance for every time.
It will update string at one place in memory and doesn’t create new space in memory.
4. Both String and StringBuilder contain Unicode characters of type Char and support an
indexer that returns Char. Because the String class is immutable, its indexer is read-only,
but the StringBuilder indexer is readable/writable.
5. Methods of the StringBuilder class

Method Description

StringBuilder.Append Appends information to the end of the current


StringBuilder.

StringBuilder.AppendFormat Replaces a format specifier passed in a string with


formatted text.

StringBuilder.Insert Inserts a string or object into the specified index of


the current StringBuilder.

StringBuilder.Remove Removes a specified number of characters from the


current StringBuilder.

StringBuilder.Replace Replaces a specified character at a specified index.

6 - 26 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Example

Output

Example

6 - 27 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

6.6 Tuple

Tuple is a data structure which consists of the multiple parts. A C# tuple is a data structure
that provides an easy way to represent a single set of data that has sequence of elements of
different data types. The System.Tuple class provides static methods to create tuple objects.
The Tuple<T> class was introduced in .NET Framework 4.0.
Tuples allow to,
Represent multiple data into single data set.
Create, access, and manipulate a data set.
Return a data set from a method without using out parameter.
Pass multiple values to a method through a single parameter.
Can store duplicate values.
Create and Access Tuples

Using Tuple<> class constructor or the "Create" method tuple can be created. The
tuple is a set of 3 data types including two strings and one int that represents an author's name,
book title, and year of publication.

6 - 28 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Nested Tuple

C# allows to create a tuple into another tuple termed as nested tuple. .NET framework
supports tuples with up to eight elements. Nested tuples are to be used when more than eight
elements are to be added in the same tuple. The nested tuple is accessible by using the Rest
property. To have a tuple with more than seven elements, the 8th element is used with the help
of Rest property, to created nesting tuple objects.

Tuple Names

A 2-tuple is called a pair. A 3-tuple is called a triple. A 4-tuple is called a quadruple. A 5-


tuple is called a quintuple. A 6-tuple is called a sextuple. A 7-tuple is called a septuple. Larger
tuples are called n-tuples.
Tuples in methods

A tuple is handy when there is need to pass a data set as a single parameter of a method
without using ref and out parameters. In code below method takes tuple as a parameter.

Returning a Tuple from method

A tuple can be used to return a data set as a single variable of a method.

6 - 29 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

A complete program using Tuple

Output

6 - 30 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Tuple Limitations

1. Tuple is a reference type and not a value type. It allocates on heap and could result in
CPU intensive operations.
2. Tuple is limited to include 8 elements. Further nested tuples have to be used.
3. Tuple can be accessed using Item <elementNumber> property only.
ValueTuple

C# 7.0 (.NET Framework 4.7) includes ValueTuple to overcome the limitations of Tuple
and also makes it even easier to work with Tuple. If ValueTuple is not seen in the project then
it needs to be installed.
ValueTuple Initialization

It is easy to create and initialize ValueTuple. It can be created and initialized using
parentheses () and specifying the values between them.

ValueTuple can also be initialized by specifying the type of each element, as shown below,

Below is the short method of declaring types for each member. In the below statement 'var'
is not used for tuple initialization statement; instead the type of each member values is
mentioned inside the brackets.

Tuple requires at least two values. The following is NOT a tuple.

Unlike Tuple, a ValueTuple can include more than eight values.

Named Members in the Tuple

Names can be assigned to ValueTuple properties instead of having the default property
names Item1, Item2 and so on.

6 - 31 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Also member names can be assigned at the right side with values,

So, the member names can be assigned either at the left side or at the right side but not at
both side. The left side has precedence over the right side. The following will ignore names at
the right side.

Variables can be assigned as member values.

ValueTuple as Return Type

The following method returns a ValueTuple.

Different member names can be specified for a ValueTuple returned from a method.

6 - 32 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Deconstruction

Individual members of a ValueTuple can be retrieved by deconstructing it. A


deconstructing declaration syntax splits a ValueTuple into its parts and assigns those parts
individually to newly created variables.

'var' can be used instead of explicit data type names.

Two Marks Questions with Answers

Q.1 What are differences between system.stringbuilder and system.string ?


Ans. : The main differences between system.stringbuilder and system.string are :
system.stringbuilder is a mutable while system.string is immutable.
Append keyword is used in system.stringbuilder but not in system.string.
Q.2 What are tuples in .Net ? How many elements a tuple can hold ?
Ans. : A tuple is a fixed-size collection that can have elements of either same or different
data types. The user must have to specify the size of a tuple at the time of declaration just
like arrays.

6 - 33 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

A tuple can hold up from 1 to 8 elements. In the case of more than 8 elements, then the
8th element can be defined as another tuple. Tuples can be specified as parameter or return
type of a method.
Q.3 What is Jagged Arrays ?
Ans. : The Array which has elements of type array is called jagged Array. The elements
can be of different dimensions and sizes. We can also call jagged Array as an Array of
arrays.
Q.4 Name some properties of Array.
Ans. : Properties of an Array include :
Length : Gets the total number of elements in an array.
IsFixedSize : Tells whether the array is fixed in size or not.
IsReadOnly : Tells whether the array is read-only or not.
Q.5 What is a String ? What are the properties of a String Class ?
Ans. : A String is a collection of char objects. We can also declare string variables in c#.
string name = "C# Questions";
A string class in C# represents a string. The properties of the string class are :
Chars get the Char object in the current String.
Length gets the number of objects in the current String.
Q.6 What is the advantage of using a StringBuilder ?
Ans. : The StringBuilder class enables to (in effect) create a mutable string that is a string
that can be changed. Existing characters can be changed, insert or add new ones or delete
characters and it's still the same object. It automatically increases its size when needed by
doubling the size of its internal buffer.
In contrast, the String class produces immutable strings. Methods which appear to
change the string do in fact return a new one.
Because StringBuilders are mutable they are useful for operations such as
concatenation on a large number of strings, where they are more performant than
ordinary strings and ease pressure on the garbage collector
So when the user needs the repetitive operations on the string then the need of
StringBuilder come into existence. It provides the optimized way to deal with the
repetitive and multiple string manipulation operations.

6 - 34 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

Long Answered Questions

Q.1 Define array and syntax for specifying the array. (Refer section 6.1)
Q.2 Discuss Array class in C#. (Refer section 6.2)
Q.3 Discuss Tuples in C#. (Refer section 6.6)
Q.4 Discuss purpose and methods of String class. (Refer section 6.4)
Q.5 What is StringBuilder class and its use ? (Refer section 6.5)
Q.6 Explain in detail about the class which can be used when you want to modify a
string without creating a new object. (Refer section 6.5)

C# - Arrays, Strings, StringBuilders and Tuples ends …

6 - 35 C# and .NET Programming


C# - Arrays, Strings, StringBuilders and Tuples

6 - 36 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Core C# and Structs.

Section No. Topic Name Page No.


7.1 Structures 7-2

7.2 Enumerations 7-7

Two Marks Questions with Answers 7-9

Long Answered Questions 7 - 10

7-1 C# and .NET Programming


C# - Structures and Enumerations

7.1 Structures

Concept

In C#, a structure is a value type user defined data type that can contain different members
as variable, method, properties etc.
Explanation

1. Structures are value type and they are stored on the stack memory.
2. Structure helps to make a single variable hold related data of various data types.
3. The struct keyword is used for creating a structure.
4. Structures are used to represent a record.
5. For using structure it should be defined first and then used. Following steps are taken to
use the structure in the program.
5.1 Defining a structure
To define a structure, ‘struct’ statement is used. The struct statement defines a new data
type, with more than one member.
Syntax

Example

5.2 Creating variable of the structure type


By using following statement book type variable is created.

7-2 C# and .NET Programming


C# - Structures and Enumerations

5.3 Assigning the values to structure members

5.4 Copying values from one structure to another structure


When object of any structure is created, the data member of that structure
automatically comes in memory. For copying values from one structure to another
structure, assignment operator is used.
Example

5.5 Using structure in a program


Example

7-3 C# and .NET Programming


C# - Structures and Enumerations

Output

7-4 C# and .NET Programming


C# - Structures and Enumerations

6. Features of C# structures
1. Structures can have methods, fields, indexers, properties, operator methods, and
events.
2. Structure members are private by default in C#. One can not access private member
from the outside of the class using dot operator.
3. Structures can have defined constructors, but not destructors. However, one cannot
define a default constructor for a structure. The default constructor is automatically
defined and cannot be changed. Because copies of structs are created and destroyed
automatically by the JIT compiler, a default constructor and destructor are
unnecessary.
4. Within a struct declaration, fields cannot be initialized unless they are declared as
const or static.
5. Unlike classes, structures cannot inherit other structures or classes.
6. All structs inherit directly from System.ValueType, which inherits from
System.Object.
7. Structures cannot be used as a base for other structures or classes.
8. A structure can implement one or more interfaces.
9. Structure members cannot be specified as abstract, virtual, or protected.
10. When struct object is created using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated without
using the New operator.
11. If the New operator is not used, the fields remain unassigned and the object cannot be
used until all the fields are initialized.
12. There can be nested structures in C#.
13. One can implement interfaces in structs but cannot inherit a struct from other struct or
class.
14. Structs are by default sealed.
15. Most of the Primitive types in .NET are Structs.
7. Class versus Structure
1. Classes are reference types and structs are value types.
2. Structures do not support inheritance.
3. Structures cannot have default constructor.

7-5 C# and .NET Programming


C# - Structures and Enumerations

8. Advantage of structure in C#
1. Structures are stored on the stack, so there are some advantage of structures, like,
structure are created more quickly than heap –allocated objects.
2. Structures are automatically deallocated, when goes out of the scope.
3. Structures are value type so that one can easily copy value type variables on the stack
memory.
9. When to prefer structure over class
Structure is preferred only in case,
1. It represents a single value.
2. Its size is smaller than 16 byte.
3. It is immutable.
4. It is required for boxing.
Example

using System;

7-6 C# and .NET Programming


C# - Structures and Enumerations

Output

7.2 Enumerations
Concept
An Enumeration is an user-defined integer type, which is used for attaching names to
Numbers. Enums are basically a set of named constants.
Explanation

1. They are declared in C# using the enum keyword.


Declaration of Enumeration -

For example

2. Using enumeration in a program


Example

Output

3. The value of first enum member by default in C# is Zero(0) and the type of an enum by
default in C# is int.

7-7 C# and .NET Programming


C# - Structures and Enumerations

4. One can assign values to enum member manually in C# as follows,

5. Declaring explicitly a base type for each enum.


The valid base types are,

Example

6. Features of enumeration
1. Every type automatically derives from and one can use
methods on Enums declared in the program.
2. Enums are value types and are created on the stack and not on the heap.
3. ‘new‘ operator is not used to create an type. Declaring an is a little
like setting the members of an array.
4. Values associated with enums can not be changed since enums are treated as
constants.
5. Enum have underlying type as Integral type (except char).
6. The default underlying type of the enumeration elements is int.
7. By default, the first enumerator has the value 0, and the value of each successive
enumerator is increased by 16.
8. Enumerations (enums) make code much more readable and understandable.
9. Enum can be declared either in a class or out side of a class as well.
10. Enum cannot inherit from other Enum.
11. Implicit and Explicit conversion are possible for enumerator.
12. Enum type can be converted to their base type. One can use explicit conversion to
convert back using Cast function. Literal values can be converted to an enum type
without any cast.

7-8 C# and .NET Programming


C# - Structures and Enumerations

Example

7. When to use enumeration


When class methods takes, as an argument a custom option then, enumeration can be used,
because it is lot more efficient and is better programming practice.

Two Marks Questions with Answers

Q.1 How will you differentiate between a Class and a Struct ?


Ans. : Although both class and structure are user-defined data types, they are different in
several fundamental ways. A class is a reference type and stores on the heap. Struct, on the
other hand, is a value type and is, therefore, stored on the stack. While the structure doesn't
support inheritance and polymorphism, the class provides support for both. A class can be
of an abstract type, but a structure can't. All members of a class are private by default,
while members of a struct are public by default. Another distinction between class and
struct is based on memory management. The former supports garbage collection while the
latter doesn't.
Given below are the differences between a Class and a Struct :

Sr. No. Class Struct

1. Supports Inheritance Does not support Inheritance

2. Class is Pass by reference (reference Struct is Pass by Copy (Value type)


type)

3. Members are private by default Members are public by default

4. Good for larger complex objects Good for Small isolated models

5. Can use waste collector for memory Cannot use Garbage collector and
management hence no Memory management

7-9 C# and .NET Programming


C# - Structures and Enumerations

Q.2 What is enum in C# ?


Ans. : An enum is a value type with a set of related named constants often referred to as an
enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data
type that is user-defined.
An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int
it has to be cast.
An enum is used to create numeric constants in the .NET framework. All the members
of enum are enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration element is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased by 1.

Q.3 Can you use tilde(~) with Enum in C# ?


Ans. :

Q.4 What is the advantage of structure in C# ?


Ans. : Structures are stored on the stack, so there are some advantage of structures.
Structure are created more quickly than heap-allocated.
Structures are automatically deallocated, when it go the out of the scope.
Structures are value type so that we can easily copy value type variables on the stack
memory.
Q.5 When do we prefer the use of structs over class ?
Ans. : We do not prefer structure if it satisfied the following statement which are given
below :
For represent a single value.
Size is smaller than 16 byte.
Immutable
For boxing

Long Answered Questions

Q.1 What are features of C# structures ? (Refer section 7.1)


Q.2 Define structures in C# along with their syntax. (Refer section 7.1)
Q.3 Discuss classes versus structures in C#. (Refer section 7.1)
Q.4 What is the purpose of enumeration ? (Refer section 7.2)
Q.5 What are the features of enumerations ? (Refer section 7.2)
C# - Structures and Enumerations ends …

7 - 10 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Object and Types - Classes and Structs.

Section Topic Name Page


No. No.
8.1 Classes and Objects, Constructor and Destructors, Types of 8-2
Classes and Various Class Memebers
8.2 Method Overloading 8 - 26
8.3 Modifiers Readonly and Constant 8 - 28
8.4 Interfaces 8 - 31
8.5 Nested Classes 8 - 33
Two Marks Questions with Answers 8 - 34
Long Answered with Questions 8 - 38

8-1 C# and .NET Programming


C# - OOP I - Classes and Objects

8.1 Classes and Objects, Constructor and Destructors, Types of


Classes and Various Class Memebers
8.1.1 Class
Concept

1. A class is a group of related methods and variables.


Explanation

2. It is like defining a blueprint for a data type. A class is a blueprint that defines the
attributes and behaviors of the objects that are created as instances of the class.
3. When a class is defined, this does not actually define any data, but it does define what the
class name means. That is, what an object of the class consists of and what operations can
be performed on that object.
4. Objects are instances of a class. The methods and variables that constitute a class are
called members of the class. On this object, defined methods and variables are used. As
many as instances of a class can be created as per requirement of the application.
5. By having a class in a program one of the basic feature of object oriented programming is
incorporated on the application.
6. Data encapsulation means that the class user or client code does not have direct access to
the data. When working with the data, the client code must use clearly defined properties
and methods accessed through an instance of the class.
Following are some of the benefits of encapsulating the data in the form creation of
class,
1. Preventing unauthorized access to the data.
2. Ensuring data integrity through error checking.
3. Creating read-only or write-only properties.
4. Isolating users of the class from changes in the implementation code.
8.1.2 Object
Concept

1. Object, is an instance of a class that is created dynamically which represents runtime


behavior of the class.

8-2 C# and .NET Programming


C# - OOP I - Classes and Objects

Explanation

2. Object is also a keyword that is an alias for the predefined type System.Object in the
.NET framework.
3. C# allows objects to be defined which can be user-defined, reference or value type, but
they all inherit directly or indirectly from System.Object. This inheritance is implicit so
that the type of the object need not be declared with System.Object as the base class.
4. Objects are of class type and object is created using new keyword as,

5. Object type is used for building generic routines. Because values of any type can be
assigned to variables of object type, object type is used mostly in designing classes that
handle objects of any type that allow code to be reused.
6. The non-generic collection classes in the .NET framework library, such as ArrayList, use
object type to define various collections.
7. An object consists of instance members whose value makes it unique in a similar set of
objects.
8. When an object is instantiated, it is allocated with a block of memory and configured as
per the blueprint provided by the class underlying the object.
9. Objects of value type are stored in stack, while those of reference type are allocated in the
heap.
10. As the execution of C# code is in the managed environment of .NET, wherein the garbage
collector provides automatic memory reclamation, it is not necessary or possible to
explicitly de-allocate memory that is allocated for objects.
11. Objects of value type are destroyed when they go out of scope, while reference type
objects are destroyed in a non-deterministic manner until the last reference to them is
removed.
12. The two operations related to objects created in C# are boxing and unboxing. Boxing
implies the conversion of value type to object and unboxing refers to the conversion from
object to a value type.
8.1.3 Working with the Classes and Objects
1. Creating and using a class

1.1 Defining Classes


1. The class is defined using the keyword class followed by the name of the class.
2. The body of the class definition is enclosed by an opening and closing curly bracket.

8-3 C# and .NET Programming


C# - OOP I - Classes and Objects

Example

1.2 Field (Class Member Variable)


Concept

1. Fields describe the real world properties of the object and hold the state of the object
Explanation

2. Objects describe things from the real world by using their characteristics, which are
related to the problems solved in the program.
3. These characteristics of the real-world object would be encapsulated in the class in
the form of variables.
4. When object is created based on certain class definition, the values of the fields
contain the characteristics of the created object (its state). These characteristics have
different values different for the different objects.
5. Declaring Fields in a Class
5.1) Apart from Local variables (these are the variables declared in the body of
some method (or block)) and Parameters (these are the variables in
parameters list passed to a method), the third type of variable is field or
instance variable.
5.2) Fields are declared in the body of the class which is always outside the body
of a single method or constructor.
5.3) General syntax for declaration of a field is,

The <modifiers> which describes the access level (describe in the following section ) of
the field as well as other modifiers like ‘const’ etc. Modifiers are not mandatory for field
declaration.
The <field_type> determines the type of a given field which can be primitive type (byte,
short, char and so on), an array or also some class type (e.g. Book or string).
The <field_name> indicates the name of the field which follows the identifier’s standard
naming convention of C# specified in earlier chapter (Refer chapter 2 – Section 2.6).
6. Scope of the field
The scope of a class field is from the start of class declaration statement and it is till
ending closing bracket of the body of the class.

8-4 C# and .NET Programming


C# - OOP I - Classes and Objects

7. Initialization during declaration


While declaring the field it is possible to assign to it an initial value which would be
treated as its default initial value. This is done similar to an assignment of value to local
variable
General syntax for initialization at the declaration time is,

Example

8. Default values of the fields


When an object is instanciated, all its field get memory allocated from the heap. During
this memory allocation time, initialization is done automatically with the default values
specified for the respective fields. The fields, which do not have explicitly specified default
value in the code, the default value specified for the .NET type is used for their initialization.
Important point to be noted is, this initialization for fields is different for the local
variables defined in methods. If a local variable in a method is not initialized or does not have
a value assigned to it, the code will result in compilation errors, which is in contrast, to a field
in a class which is automatically zeroed (depending on its type) by the compiler if not
initialized.
The initial default value of all types is 0 or something similar which are listed below.
Type of the field Default value
bool False
byte 0
char '\0'
decimal 0.0M

double 0.0D
float 0.0F

8-5 C# and .NET Programming


C# - OOP I - Classes and Objects

int 0

object reference Null

Table 8.1.1 Default values of the fields


9. Static and instance initialization
1. Static fields and static properties are data members associated with the class itself,
rather than with the instances of that class.
2. A static constructor can be used to initialize static members.
3. Static fields can be initialized at the time of their declaration.
4. The first time when a static member is referred, the following events take place,
1. All static fields are initialized to their respective default values.
2. The static constructor is called.
3. Code that accesses the static member is executed.
5. In case of reference to an instance method or during the instance creation of the class,
before referencing any static members, the following events take place,
1. All static fields are initialized to their respective default values.
2. The static constructor is called.
3. All instance fields are initialized to their respective default values.
4. The instance constructor is called.
5. Code that accesses an instance member is executed.
1.3 Properties
Concept

1. Properties are named members of classes, structures and interfaces. Property is


mechanism by which field in a class is protected through specialized reading and writing
method.
Explanation

2. Member variables in a class or structures are called Fields and properties are extension
of fields and are accessed using the same syntax.
3. Property use accessors through which the values of the private fields can be read, written
or manipulated.
4. Specialized getter and setter methods are implemented for field for accessing it.

8-6 C# and .NET Programming


C# - OOP I - Classes and Objects

5. Properties do not name any storage location but they have accessors that read, write or
compute their values.
6. Accessors
1. The accessor of a property contains the executable statements that helps in getting
(reading or computing) or setting (writing) the property.
2. The accessor declarations can contain a ‘get’ accessor, a ‘set’ accessor or both.
7. Benefit of properties over fields is that their internal implementation can be changed over
time.
8. If the field is public, the underlying data type must always be the same because calling
code depends on the field being the same. However, with a property, the implementation
can be changed. For example, if a Book has an ID that is originally stored an int, and now
additionally it is required to put restriction on it that it should never be negative, then it is
easily achieved through property. If it was a field, it is not possible do this, but a property
allows to make such a change.
9. Types of properties
1. Read-only Properties
Properties that can be only read and never written are called as read-only. This is
accomplished by having only a get accessor in the property implementation.
2. Write only property
Write only is the property to which values can be assigned but can never be read. A
write-only property only has a set accessor.
3. Abstract Properties
An abstract class may have an abstract property, which should be implemented in the
derived class.
10. Auto-implemented property
C# 3.0 introduced a new syntax for a property, called an auto-implemented property,
which allows to create properties without get and set accessor implementations.
Example

8-7 C# and .NET Programming


C# - OOP I - Classes and Objects

1.4 Class Fields/Properties and access modifiers


Concept

1. The variables defined inside the class are called as instance variables or member
variables (often referred to as fields). These variables hold the data that an instance of the
class will manipulate.
2. Access Modifiers (Access Specifiers)
2.1 Access Modifiers (Access Specifiers) describes the scope of accessibility of an
Object and its members.
Explanation

2.2 All C# types and type members have an accessibility level.


2.3 One can control the scope of the member object of a class using access specifiers.
Access modifiers are used for providing security in the applications.
2.4 Accessibility of a type or member is declared by using any of the access modifiers
provided by C# language.

8-8 C# and .NET Programming


C# - OOP I - Classes and Objects

2.5 C# provide five access specifiers , namely, public, private , protected , internal and
protected internal.
2.5.1 public

public is the most common access specifier in C#. Publically declared


member can be accessed from anywhere, that means there is no restriction on
accessibility. The scope of the accessibility is inside class as well as outside.
The member can be accessed by any other code in the same assembly or
another assembly that references it.
2.5.2 private

The scope of the accessibility is limited only inside the classes in which they
are declared. The private members cannot be accessed outside the class and it
is the least permissive access level.
Example

When a user of the class needs to query or set the value of these private
instance variables, public properties are exposed to them. Inside the property
block of code Get method and a Set method are added. The Get method
returns the value of the private instance variable to the user of the class. This
provides a readable property. The Set method provides a write-enabled
property; it passes a value sent in by the user code to the corresponding
private instance variable.
Example

8-9 C# and .NET Programming


C# - OOP I - Classes and Objects

2.5.3 protected

The scope of accessibility is limited within the class and the class derived
(Inherited )from this current class called as base class.
2.5.4 internal

The internal access modifiers can access within the program that contain its
declarations and also access within the same assembly level but not from
another assembly.
2.5.5 protected internal

Protected internal is the same access levels of both protected and internal. It
can be accessed anywhere in the same assembly and in the same class also the
classes inherited from the same class.
1.5 Creating Class Methods

Class method defines the behavior of the class that is method encapsulates the operations
that can be performed on the class properties.

8 - 10 C# and .NET Programming


C# - OOP I - Classes and Objects

1.6 Creating instance of a class

Using new operator instance that is object of class is created. Operator new allocates
memory for the object for its storage.
Book b;
Above statement only creates reference of Book type but no memory is allocated.
Book b = new Book();
Above statement actually allocates the memory for the reference b of type Book.
2. Constructors
Concept

1. In OOP, constructors are specialized methods used to perform any processing that
needs to occur when an object instance of the class is instantiated.
2. The class constructor method is named the same as the class and it is invoked
automatically upon creation of the object.
Explanation

3. Properties of Constructor
3.1 A class can have any number of constructors (that is constructor can be
overloaded).
3.2 A constructor doesn't have any return type, not even void.
3.3 A static constructor can not be a parametrized constructor.
3.4 Within a class one can create only one static constructor.
3.5 The main use of constructors is to initialize private fields of the class while
creating an instance for the class.
3.6 When constructor is not defined in the class, then the compiler automatically
creates a default constructor in the class.
The default constructor initializes all numeric fields in the class to zero and
all string and object fields to null.
4. There are 5 types of constructors namely,
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

8 - 11 C# and .NET Programming


C# - OOP I - Classes and Objects

4.1 Default Constructor

A constructor without any parameters is called a default constructor that is default


constructor does not take any parameters.
The limitation of default constructor is that every instance of the class will be initialized
to the same values.
Example

Output

4.2 Parameterized Constructor

A constructor with at least one parameter is called a parametrized constructor. The


advantage of a parametrized constructor is that each instance of the class can initialized to
different values as per requirement.

8 - 12 C# and .NET Programming


C# - OOP I - Classes and Objects

Output

4.3 Copy Constructor

The constructor which creates an object by copying variables from another already created
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.
Example

8 - 13 C# and .NET Programming


C# - OOP I - Classes and Objects

4.4 Static Constructor

A constructor can be created as a static constructor.


Static constructor is invoked only once for all of instances of the class and it is invoked at
the time the creation of the first instance of the class or the first reference to a static member in
the class.
A static constructor is used to initialize static fields of the class and to write the code that
needs to be executed only once in the lifetime of the class.
Properties of static constructor

1. A static constructor does not have any access modifiers and do not have any parameter.
2. A static constructor is called automatically to initialize the class before the first instance
of the class is created or any static members are referenced.
3. A static constructor cannot be called directly and programmer has no control on when the
static constructor is executed in the program.
4. A typical use of static constructors is when the class is using a record file and the
constructor is used to write entries to this record file. That is static constructor is used
when same data items are required be shared.
Example

8 - 14 C# and .NET Programming


C# - OOP I - Classes and Objects

4.5 Private Constructor

When a constructor is created with a private specifier, it is not possible for other classes to
derive from this class, neither it is possible to create an instance of this class. Such a class
containing private constructor are usually used in classes that contain static members
only.
Properties of private constructor

1. Private constructor is used when class contains only static members.


2. It provides an implementation of a singleton class pattern
3. Once there is a constructor in the class that is either private or public or any, the compiler
will not add the parameter-less public constructor to the class.

8 - 15 C# and .NET Programming


C# - OOP I - Classes and Objects

5. A constructor can call another constructor


A constructor can call another constructor, which can come in handy in several situations.
Example

3. Destructor
Concept

1. A destructor is class member method that runs after a class becomes unreachable.
Explanation

2. It has the special "~" character preceding its name.


3. The exact time it is executed is not specified. But it always runs when the class is not
reachable in memory by any references.
4. ‘Destructors’ are used to destruct instances of classes.
5. A class can only have one destructor.
6. Destructors cannot be inherited or overloaded.
7. Destructors cannot be called. They are invoked automatically.

8 - 16 C# and .NET Programming


C# - OOP I - Classes and Objects

8. A destructor does not have modifiers or nor take parameters and can not return any value.
9. The programmer has no control on when the destructor is going to be executed because
this is determined by the C# Garbage Collector. The garbage collector checks for objects
that are no longer being used by the application. It considers these objects eligible for
destruction and reclaims their memory.
10. Also when program exits the destructors are called. In the background when a destructor
executes, the destructor implicitly calls the Object.Finalize method on the object's base
class.
11. To call the destructor intentionally once task is finished, there are two ways :
i) Call the Garbage collector to clean up by calling the GC.Collect method, generally,
this should be avoided as it may result in performance issues.
ii) Implement Dispose method of IDisposable interface. The IDisposable interface
contains only one public method with signature void Dispose() which when
implemeted can close or release resources such as files, streams, and handles held by
an instance of the class that implements this interface.
class

public void

//implementation

12. The ‘using’ method


When an object that encapsulates any resource, one should make sure that, the object's
Dispose method is called. This can be done more easily using the ‘using’ statement in C#.

When the control exits from the using block either by running successfully and reaching
the closing braces or by throwing an exception, the IDispose.Dispose() of Book will be
executed provided the object being instantiated must implement the System.IDisposable
interface. The using statement defines a scope at the end of which an object will be disposed.
The using statement obtains the resource specified, executes the statements and finally calls
the Dispose method of the object to clean up the object.

8 - 17 C# and .NET Programming


C# - OOP I - Classes and Objects

Example

4. Members of Class
Following is the complete list of the types of members one can have in classes,
1. Constructors
2. Destructors
3. Fields
4. Methods
5. Properties
6. Indexers
7. Delegates
8. Events
9. Nested Classes
5. Types of classes in C#
Concept

Apart from being a normal instanciable class, class can be of following types,
1. Abstract class 2. Partial class 3. Sealed class 4. Static class 5. Unsafe class
5.1 Abstract Class (A pure virtual class)
Concept

1. An abstract class is the one whose object can not be created that is it is non-instanciable
class.
Explanation

2. Abstract class can be derived that is it can be inherited. It can serve the purpose of
base/super class only as no object of this class can be created.
3. Abstract Class is denoted by the keyword abstract.
4. Abstract class can have non-abstract method(s) that is methods with implementation or
can have non-abstract method(s) that is methods without any implementation. The
implementation of non-abstract method would be later given by inherited classes which
are derived from this abstract class. When an abstract class is derived from another

8 - 18 C# and .NET Programming


C# - OOP I - Classes and Objects

abstract class, then, in the derived class, it is optional to implement the abstract method(s)
of the base/super class.
Example

Example

8 - 19 C# and .NET Programming


C# - OOP I - Classes and Objects

5.2 Partial Class


Concept

1. Partial Class is class that allows its members - method, properties, and events - to be
divided into multiple source files which have extension ‘.cs’. At compile time these
several files get combined into a single class.
Explanation

2. It is a special type of class called "Partial Class" which was newly introduced with .Net
Framework 2.0.
3. Partial Class is denoted by the keyword partial.
4. Important some do's and don'ts about partial class
i. All the parts of a partial class must be prefixed with the keyword partial.
ii. Accessibility, signature etc. must be same in all parts of the partial class.
iii. One cannot sealed one part of the partial class. In that case entire class is sealed.
iv. If any part of the partial class is defined abstract, entire class will become abstract.
v. Inheritance cannot be applied to a part of partial class. If applied then it is applicable
to entire class.
Example

8 - 20 C# and .NET Programming


C# - OOP I - Classes and Objects

5.3 Sealed Class


Concept

1. A sealed class is a class which cannot be inherited.


Explanation

2. A sealed class cannot be a base class to any other class. The modifier abstract cannot be
applied to a sealed class otherwise it would be un-useful class that is it can not be
inherited and can not be instantiated as well.
3. By default, struct (structure) is sealed. It is the last class in hierarchy. To access the
members of a sealed class, one must create objects of that class.
4. Sealed Class is denoted by the keyword sealed.
Example

5.4 Static Class


Concept

1. A Static Class is one which cannot be instantiated that is its object can not be created.
Explanation

2. The keyword new cannot be used with static classes as members of such class can be
called directly by using the class name itself.
3. Main characteristics of a static class
i) A Static Class can only have static members.
ii) A Static Class cannot be instantiated.

8 - 21 C# and .NET Programming


C# - OOP I - Classes and Objects

iii) A Static Class is sealed therefore cannot be inherited.


iv) A Static Class cannot have any constructor except static constructor.
v) Static Class is denoted by the keyword static.
vi) Static class is useful when ready to use method implementations are to be provided
or there are common variables that are to be shared among multiple objects.
Example

5.5 Unsafe class


Concept

1. A class that contains unsafe code is declared as unsafe .


Explanation

2. C# allows using pointer variable, in a member method or as a member variable. When


such member exists then the class containing it is declared to be unsafe. Only the method
containing unsafe code can also be marked by the unsafe modifier.
3. The unsafe code or the unmanaged code is a code block that uses a pointer variable.
Example

8 - 22 C# and .NET Programming


C# - OOP I - Classes and Objects

8.1.4 this Reference


Concept

1. The ‘this’ keyword is a special type of reference variable, that is implicitly defined within
each constructor and non-static method as a first parameter of the type class in which it is
defined.
Explanation

2. The reference variable ‘this’ is allocated within the method stack whenever a non-static
method or constructor is called. That is ‘this’ reference variable can be allocated several
times to hold the address of a single object.
3. The reference variable ‘this’ is automatically initialized with the reference of the current
object for which the non-static method or constructor is called.
4. It is a keyword, which is used for eliminating naming conflicts.
5. It indicates the current instance.
6. Two variables can have the same identifier. To eliminate the naming conflicts this
keyword can be used.
7. This cannot refer to a static field or method. It cannot occur inside a static class.
8. Extension method represents a static method as an instance method. An extension method
uses the this-keyword in its parameter list. It must be located in a static class.
Example

9. ‘this’ keyword is inferred by the compiler and not required to be specified explicitly.
10. 'this' can be used in a constructor initializer to implement constructor overloading and
code sharing.
11. 'this' can be used to declare an indexer.
Example

8 - 23 C# and .NET Programming


C# - OOP I - Classes and Objects

8.1.5 Indexer
Concept

1. An indexer is a method implemented that allows an object to be indexed just like an


array.
Explanation

2. When an indexer is defined for a class, this class behaves similar to a virtual array. Now,
the instance of this class can be accessed using the array access operator ([ ]).
3. An indexer provides array-like syntax. It allows a type to be accessed the same way as an
array. Properties such as indexers often access a backing store.
4. Indexer modifier can be private, public, protected or internal.
5. The return type of indexer can be any valid C# types.
6. Indexers in C# must have at least one parameter, else the compiler will generate a
compilation error.
7. In an indexer, often a int parameter is accepted and it accesses a backing array. Values in
indexer can be initialized with an initializer.
8. Indexer can be overloaded that is there can be multiple indexer in the class.
9. General syntax of Indexer

8 - 24 C# and .NET Programming


C# - OOP I - Classes and Objects

Example

8 - 25 C# and .NET Programming


C# - OOP I - Classes and Objects

8.2 Method Overloading

Concept

1. Overloading methods in a class means one can define multiple methods that have the
same name but contain different signatures.
Explanation

2. The ability to overload methods is a useful feature of OOP languages.


3. A method signature is a combination of the name of the method and its parameter type
list. If the parameter type list is changed, different method signature is created. For
example, the parameter type lists can contain a different number of parameters or different
parameter types.
4. The compiler will determine which method to execute by examining the parameter type
list passed in by the client code.
5. The method signature is considered different when either number of parameters are
changed or datatype of parameters are changed.
6. Following points should be noted which specify that in which case signature is not
considered to be altered :
i) Changing how a parameter is passed (in other words, from byVal to byRef) that is
which method of parameter passing is used, does not change the method signature.
ii) Altering the return type of the method also does not create a unique method
signature.
7. Constructors are though special but class methods they can also be overloaded same like
other methods.

8 - 26 C# and .NET Programming


C# - OOP I - Classes and Objects

Example

Example

8 - 27 C# and .NET Programming


C# - OOP I - Classes and Objects

8.3 Modifiers Readonly and Constant

Concept

1. The variable or fields, declared as const or readonly are called constants whose value
can't be changed.
Explanation

2. They are used when a certain value is used several times.


3. These values are declared only once without repetitions.
Examples of some default constants in the .NET Framework are the mathematical
constants Math.PI and Math.E.
4. Const Modifier
I) Const variable
Concept

1. The const keyword is used to modify a declaration of a local variable which


specifies that the value of the local variable cannot be modified.
2. Multiple constants can be declared in the same statement as shown below,

3. Constant Declaration Syntax

Example :

4. Constants can be byte, char, short, int, long, float, double, decimal, bool, string, an
enum type, or a reference type.
5. A constant expression is an expression that can be fully evaluated at compile time.
Therefore, the only possible values for constants of reference types are string and
null.
6. A constant can participate in a constant expression as given below :

7. A constant expression must yield a value of the target type, or of a type that can be
implicitly converted to the target type.

8 - 28 C# and .NET Programming


C# - OOP I - Classes and Objects

8. The static modifier is not allowed in a constant declaration.


II) Const Data Members
Concept

1. The const keyword is used to modify a declaration of a local variable which


specifies that the value of the local variable cannot be modified.
Explanation

2. Const data members are static and only can be used with class reference and
the const data member name.
3. The fields, declared with const, have to be initialized during the declaration
and afterwards theirs value cannot be changed.
4. They can be accessed without creating instance (an object) of the class and
they are shared among all the created objects for the same class.
5. When code is compiled, the places where const fields are referred are replaced
with their actual specified values directly so that constant variable need not be
accessed again and again while referred (this would contribute to saving the
runtime). This is the reason why the const fields are called compile-time
constants, as they are replaced with the value during the compilation process.
Constant Declaration Syntax

Example :

Here,
Attribute and Modifier is optional.
The attributes and modifiers apply to all of the members declared by the
constant declaration.
5. Readonly Data Members
Concept

1. Readonly are instance data members whose value can not be altered by calling code.
Explanation

2. A readonly data member can't be made as a property.


3. Fields, declared as readonly, allow one-time initialization either at the time of the
declaration or in the class constructors. Later theirs values cannot be changed.

8 - 29 C# and .NET Programming


C# - OOP I - Classes and Objects

Therefore, the readonly fields are called run-time constants - constants, because
their values cannot be changed after assignment and run-time, because this process
happens during the execution of the program.
4. It can be changed in class constructor only.
5. When a field declaration includes a readonly modifier, the assignments to the fields
introduced by the declaration can only occur as part of the declaration or in a
construction in the same class.
6. Assigning value to readonly member
Readonly variable can be initialized at declaration time.

Readonly instance field can be initialized ,in the instance constructors of the class that
contains the field declaration.
A static readonly field can be initialized , in the static constructor of the class that
contains the field declaration .
Readonly field can be passed as an out or ref parameter.
6. Example (modifier - readonly and const)

8 - 30 C# and .NET Programming


C# - OOP I - Classes and Objects

8.4 Interfaces

Concept

1. An interface is similar like a class, but has no implementation of any method in it.
Explanation

2. Interface contains only the declarations of methods, properties, indexers and events.
3. Interfaces only provide declarations that are being implemented by the classes and structs
which are derived from these interfaces. Classes and structs, which derive these interface
must provide an implementation for each interface member declared.
4. The interface defines the 'what' part of the object being implemented and the deriving
classes define the 'how' part of it.
5. Interfaces are much like abstract classes in the sense that no instances of interface can be
created. But the major difference is that abstract classes may contain implementation for
some methods where as interfaces can not have implementation for even a single method.
All the methods in interfaces are abstract only.
6. As there are no methods in interfaces there is no need for any fields/instance variable as
well. Still interfaces may contain properties, indexers and events.
7. Interface is like a contract - a class that implements it is required to implement all of the
methods and properties. However, the most important difference is that while C#
doesn't allow multiple inheritance for classes, it does allow for implementation of
multiple interfaces.
8. Interfaces provide a way to achieve runtime polymorphism. Using interface, functions
from different classes can be invoked through the same interface reference. Using virtual
functions, functions from different classes in the same inheritance hierarchy can be
invoked through the same reference.

8 - 31 C# and .NET Programming


C# - OOP I - Classes and Objects

9. Declaring and using interface


Interface is declared using keyword ‘interface’. For using the interface it should be
inherited as well as implemented in the deriving class.
10. Naming the interface
Interface types are usually named with a first letter I. There is no language-based
constraint but it is a convention.
Example

Output

8 - 32 C# and .NET Programming


C# - OOP I - Classes and Objects

8.5 Nested Classes

Concept

1. A class can be created inside of another class that is a class created inside of another is
referred to as nested that is one class encloses another class.
Example

Explanation

2. As many classes can be nested as required in another class until it is manageable.


3. One can declare all necessary fields, properties or methods in the nested class (one which
is inside class) or in the nesting class. When one class is created inside of another, there is
no special programmatic relationship between both classes : Just because a class is nested
does not mean that the nested class has immediate access to the members of the nesting
class. They are two different classes and they can be used separately as per need.
4. The name of a nested class is not "visible" outside of the nesting class. To access a nested
class outside of the nesting class, one must qualify the name of the nested class while
using it.
5. As there is no programmatically privileged relationship between a nested class and its
"container" class, if one want to access the nested class in the nesting class, one can use its
static members.
6. Nested class should be used when the class is useful to the enclosing class.

8 - 33 C# and .NET Programming


C# - OOP I - Classes and Objects

Two Marks Questions with Answers

Q.1 Explain the difference between a class and an object.


Ans. :
Sr. No.
Class Object

1. Class is the definition of an object An object is an instance of a class.

2. It is a template of the object A class does not become an object


unless instantiated

3. It describes all the methods, properties, etc An object is used to access all those
properties from the class.

8 - 34 C# and .NET Programming


C# - OOP I - Classes and Objects

Q.2 Differentiate between constants and read-only variables.


Ans. :
Sr. No. Constants Read-only Variables

1. Evaluated at compile time Evaluated at run-time


2. Support only value type variables They can hold the reference type
variables
3. They are used when the value is not Used when the actual value is
changing at compile time unknown before the run-time
4. Cannot be initialized at the time of Can be initialized at the time of
declaration or in a constructor declaration or in a constructor
Q.3 What are the different types of constructors in C# ?
Ans. : Following are the types of constructors in C# :
Default constructor
Parameterized constructor
Copy constructor
Static constructor
Private constructor
Q.4 Difference between interface and abstract class in .NET ?
Ans. :

Sr. No. Interface Abstract class

1. An interface merely declares a An abstract class provides a partial


contract or behavior that implementation for a functionality
implementing classes should have. that must be implemented by the
inheriting entities.
2. An interface may declare only An abstract class declares fields
properties, methods and events with too.
no access modifier.
Q.5 Explain the modifiers sealed, static, unsafe, abstract.
Ans. : These modifiers are used to refine the declaration of a class as mentioned below,
Sealed - The class stops inheriting by any derived class.
Static - The class contains only static members.
Unsafe - The class that stores unsafe types likes pointers.
Abstract - No instance of the class if the Class is abstract.

8 - 35 C# and .NET Programming


C# - OOP I - Classes and Objects

Q.6 Define interfaces.


Ans. : Interface in C# is a blueprint of a class. Like a class, Interface can have methods,
properties, events, and indexers as its members. But interfaces will contain only the
declaration of the members. The implementation of interface's members will be given by
class who implements the interface implicitly or explicitly.
It is like abstract class because all the methods which are declared inside the interface are
abstract methods. It cannot have method body and cannot be instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to
achieve fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which
implements the interface, must provide the implementation of all the methods declared inside
the interface.
Q.7 Can “this” be used within a static method ? Justify your answer.
Ans. : ‘this’ cannot be used in a static method because static method does not need any
object to be called, and ‘this’ keyword always points to a current object of a class.
A static method in C# is a method that keeps only one copy of the method at the Type
level, not the object level. That means, all instances of the class share the same copy of the
method and its data. The last updated value of the method is shared among all objects of
that Type. Static methods are called by using the class name, not the instance of the class.
Hence, if there is no object available then how ‘this’ would point to any current object.
So the use of ‘this’ keyword is not allowed inside static method.
Q.8 Recall early binding and late binding.
Ans. : Early Binding (Static binding)
When perform Early Binding, an object is assigned to a variable declared to be of a
specific object type. Early binding objects are basically a strong type objects or static type
objects. While Early Binding, methods, functions and properties which are detected and
checked during compile time and perform other optimizations before an application
executes. The biggest advantage of using early binding is for performance and ease of
development.
Example,

In above code, a variable objFS is created to hold a new object and then assign a new
object to the variable. Here type is known before the variable is exercised during run-time,
usually through declarative means. The FileStream is a specific object type, the instance

8 - 36 C# and .NET Programming


C# - OOP I - Classes and Objects

assigned to FS is early bound. Early Binding is also called static binding or compile time
binding.
While performing Early Binding the compiler can ensure at compile time that the function
will exist and be callable at runtime. Moreover the compiler guarantees that the function
takes the exact number of arguments and that they are of the right type and can checks that
the return value is of the correct type.
Late binding (Dynamic binding)

By contrast, in late binding functions, methods, variables and properties are detected
and checked only at the run-time. It implies that the compiler does not know what kind of
object or actual type of an object or which methods or properties an object contains until
run time. The biggest advantages of late binding is that the Objects of this type can hold
references to any object, but lack many of the advantages of early-bound objects

Above code does not require a reference to be set beforehand, the instance creation and
type determination will just happen at runtime. It is important to note that the late binding
can only be used to access type members that are declared as Public. Accessing members
declared as Friend or Protected Friend resulted in a run-time error.
While perform late binding there is a possibility of the target function may not exist.
Also the target function may not accept the arguments passed to it, and may have a return
value of the wrong type.
Method Overloading (Early binding) and Method Overriding (Late Binding)

Method Overloading happens at compile time (Early Binding) while Overriding


happens at runtime (Late Binding). In method overloading, method call to its definition has
happens at compile time (Static Binding) while in method overriding, method call to its
definition happens at runtime (Dynamic Binding).
Q.9 What are sealed classes ?
Ans. : A sealed class, in C#, is a class that cannot be inherited by any class but can be
instantiated.
The design intent of a sealed class is to indicate that the class is specialized and there is
no need to extend it to provide any additional functionality through inheritance to override
its behavior. A sealed class is often used to encapsulate a logic that needs to be used across
the program but without any alteration to it.

8 - 37 C# and .NET Programming


C# - OOP I - Classes and Objects

A sealed class is mostly used for security reasons by preventing unintended derivation
by which the derived class may corrupt the implementation provided in the sealed class. As
the sealed class cannot form a base class, calls to sealed classes are slightly faster because
they enable certain runtime optimizations such as invocation of virtual member functions
on instances of sealed class into non-virtual invocations. Sealed class helps in versioning
by not breaking compatibility while changing a class from sealed type to unsealed.
Sealed class is used to define the inheritance level of a class. The sealed modifier is used
to prevent derivation from a class. An error occurs if a sealed class is specified as the base
class of another class.
Properties of sealed class,
1. A class, which restricts inheritance for security reason is declared sealed class.
2. Sealed class is the last class in the hierarchy.
3. Sealed class can be a derived class but can't be a base class.
4. A sealed class cannot also be an abstract class. Because abstract class has to provide
functionality and here it is being restricted to inherit.
Q.10 What is a constructor ?
Ans. : In C#, constructor is a special method which is invoked automatically at the time
when the object is created. It is used to initialize the data members of new object generally.
The constructor in C# has the same name as class or struct.
There can be two types of constructors in C#.
Default constructor - A constructor which has no argument is known as default
constructor. It is invoked at the time of creating object.
Parameterized constructor - A constructor which has parameters is called
parameterized constructor. It is used to provide different values to distinct objects.
Long Answered Questions

Q.1 Discuss method overloading. (Refer section 8.2)


Q.2 What are nested classes ? (Refer section 8.5)
Q.3 Discuss indexers in C#. (Refer section 8.3)
Q.4 What are interfaces and how they differ from classes ? (Refer section 8.4)
Q.5 Discuss modifiers - readonly and constants. (Refer section 8.3)
Q.6 Explain constructors and its types and show how to add a constructor to the
building class. (Refer section 8.1)
Q.7 Explain indexers and index overloading in C#. Write a C# program to implement
overloaded indexers with the days of a week. (Refer section 8.1)

8 - 38 C# and .NET Programming


C# - OOP I - Classes and Objects

Q.8 Create a class called employee that includes three pieces of information as
data members a first name (type string), a last name (type string) and a monthly
salary (type int). The class should have a constructor that initializes the three
data members. Provide a set and a get function for each data member. If the
monthly salary is not positive, use exception handling. Write a C# program that
demonstrates class employee’s capabilities. Create two employee objects and
display each object’s yearly salary. Then give each employee a 10 percent raise
and display each employee’s yearly salary again. (Refer section 8.1)

Q.9 Consider 2 toll booths in a national highway. People passing by are to pay
30/-. The booths keeps track of the number of people who visited the booth and
the total ticket amount collected. Model the toll booth with a class called
TollBooth in C# with the following members.
Data Members
Numbers of people who visited the booth
Total amount collected
Member Functions
Increment number of people and amount of someone passes by
Display the result
Exception : The number of people has to be a valid integer.
Use appropriate constructors and destructor. Use the concept of threads to
implement the 2 booths (Refer section 8.1)

C# - OOP I - Classes and Objects ends …

8 - 39 C# and .NET Programming


C# - OOP I - Classes and Objects

8 - 40 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Inheritance-Generics.

Section No. Topic Name Page No.


9.1 Inheritance 9-2

9.2 Polymorphism and Runtime Behaviours 9 - 17

9.3 Overriding Methods 9 - 20

9.4 Hiding Method 9 - 24

9.5 Combining Method Overriding and Method Hiding 9 - 26

9.6 Operator Overloading 9 - 27

9.7 Generics 9 - 32

Two Marks Questions with Answers 9 - 39

Long Answered Questions 9 - 41

9-1 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9.1 Inheritance

9.1.1 Designing Base and Derived Classes


Concept

1. Inheritance is a mechanism of sharing the members among the classes.


Explanation

2. Inheritance is one of the primary concepts of object-oriented programming.


3. It allows, to reuse existing code. Through effective employment of reuse, one can save
time in programming.
4. Inheritance allows to define a class in terms of another class, which makes it easier to
create and maintain an application and speeds up implementation time.
5. While creating a new class, instead of writing completely new data members and member
functions, it would be specified that the new class should inherit the members of an
existing class. This existing class is called the base class, and the new class is referred to
as the derived class.
6. Inheritance implements the IS-A type of relationship that may exists among multiple
objects of similar kind with certain changes in their characteristics.
For example, Depositor IS A Customer, Borrower IS-A Customer.
7. Base and Derived Classes
A class can be derived from more than one class or interface (would be discussed in
section…..) , which means that it can inherit data and method/functions from multiple
base classes or interfaces.
The syntax used in C# for creating derived classes is as follows:

9.1.2 Types of Inheritance

In C# inheritance may be implemented in different ways as shown in figure,


1. Single Inheritance

9-2 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (The Multiple inheritance is not directly implemented by C#. But it
can be implemented using the concept of multiple inheritance for interface)

Fig. 9.1.1 Types of inheritance

9.1.2.1 Single Inheritance


Concept

In single inheritance as the name implies one single class (derived) derives another existing
class (base).
Example

9-3 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.1.2.2 Multilevel Inheritance


Concept

In this inheritance the level of inheritance increases and one class derives another class
which in turn is derived from some other class.
Example

9-4 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.1.2.3 Hierarchical Inheritance


Concept

In this type inheritance more than one classes have been derived from single base class
yielding hierarchy like structure.
Example

9-5 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.1.2.4 Multiple Inheritance

In C# multiple inheritance is not supported for classes. That is one class can not inherit
multiple classes. But one class is allowed to inherit single class and more than one interface.
This is termed as multiple inheritance.

9-6 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9-7 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9.1.3 Access Modifiers

1. Class inheritance combines interface inheritance and implementation inheritance.


Interface inheritance defines a new interface in terms of one or more existing interfaces.
Implementation inheritance defines a new implementation in terms of one or more
existing implementations.
2. Access modifiers for a class member give different levels of access to derived classes.
Below table describes the access a derived class has to the members of the inherited class
depending upon the access modifier.

Parent class access modifier Access in child class

public accessible

protected accessible

private not accessible

Table 9.1.1 Access modifiers and scope in inheritance


Example

9-8 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9-9 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9.1.4 Visibility Modifiers in C#


Concept

Visibility control is a key issue in object-oriented programming. Visibility-control is


important because it protects the invisible parts of a class from being directly accessed from
other classes. No other parts of the program can rely directly on details, which they cannot
access. If some detail (typically a variable) of a class cannot be seen outside the class, it is
much easier to modify this detail at a later point in time.
Explanation

Visibility of types in assemblies and visibility of members in types

Visibility of a type (for example, a class) in an assembly.


internal: The type is not visible from outside the assembly.
pu The type is visible outside the assembly.
Visibility of members in type (for example, methods in classes).
Accessible only in the containing type.
Accessible in the containing type and in subtypes.
Accessible in the assembly.
Accessible in the assembly and in the containing type and
its subtypes.
Accessible whenever the enclosing type is accessible.

9.1.5 Class Modifiers


Concept

1. While implementing inheritance, it is important to understand how to establish


accessibility level for newly designed derived classes and their members.
Explanation

2. Class modifier is used to decide which parts of the system can create class objects.
There are four different-optional-class modifiers which are,
1. public - The 'public' keyword identifies a type as fully accessible to all other types.
This is the implicit accessibility of enumeration members and interface members.
2. internal - If a class is declared as 'internal', the type it defines is accessible only to
types within the same assembly (a self-contained 'unit of packaging' containing code,
metadata etc.). This is the default access level of non-nested classes.

9 - 10 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

3. protected - If a class is declared as 'protected', its type is accessible by a containing


type and any type that inherits from this containing type. This modifier should only
be used for internal classes (i.e. classes declared within other classes).
4. private - Where a class is declared as 'private', access to the type it defines is limited
to a containing type only. This modifier should only be used for internal classes (ie.
classes declared within other classes).
These are used to specify the access levels of the types defined by the classes.
3. Also, the following different access levels can be specified with above four modifiers,
1. Protected internal - The permissions allowed by this access level are those allowed
by the 'protected' level plus those allowed by the 'internal' level. The access level is
thus more liberal than its parts taken individually. This modifier should only be used
for internal classes (ie. Classes declared within other classes).
2. New - The 'new' keyword can be used for 'nested' classes. A nested class is one that
is defined in the body of another class; it is in most ways identical to a class defined
in the normal way, but its access level cannot be more liberal than that of the class in
which it is defined. A nested class should be declared using the 'new' keyword just in
case it has the same name as (and thus overrides) an inherited type.
3. Abstract - A class declared as 'abstract' cannot itself be instanced - it is designed
only to be a base class for inheritance.
4. sealed - A class declared as 'sealed' cannot be inherited from other classes. It is an
error to use a sealed class as a base class. Use the sealed modifier in a class
declaration to prevent inheritance of the class.
9.1.6 Constructor and Destructor Calling Order in C# Inheritance Hierarchy

1. When a derive class is instantiated, the default constructor of the base class is called
automatically. In this way, the base constructor can initialize the base class before
the derive class’s constructor is executed.
Example

9 - 11 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

2. Calling base class constructor in C#


During inheritance, if the base class contains only parameterized constructor, then derived
class must contain a parameterized constructor even if it doesn’t need one.
In this case while creating parameterized constructor in derived class, one should specify the
parameters required for derived class along with the parameters required for base class
constructor and to pass arguments to base class constructor, using the keyword “base” at the
end of parameterized constructor declaration in derived class preceded with “:”.
If one derives a class from a base class and want to pass data from the constructor of the
derived class to the constructor of the base class, it is necessary to call base constructor.
In the inheritance hierarchy, always the base class constructor is called first. In c#, the base
keyword is used to access the base class constructor as shown below.

9 - 12 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

3. Private Constructors
Private constructors are the constructors with the "private" access modifier. If there is
private constructor in the class, then, one can neither create the object of the class, nor can
inherit the class.

9 - 13 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

There can be constructors along with the constructors in the class and the
constructors can access the constructors from within the class through
constructor chaining.

When to use class with only private constructor

It is possible to have the class with only the private constructors. Main use is in the case
when there are only static members in the class and class would never be instantiated.
4. Initialization in Static Constructors
1. A static constructor is used to initialize any static data, or to perform a particular
action that needs to be performed once only.
2. Static constructor is called automatically before the first instance is created or any
static members are referenced.
3. There can be only one static constructor in the class as overloading needs the two
methods to be different in terms of methods definition, which cannot be done with
static Constructors.
4. The static constructor should be without parameters, as it is going to be called by
CLR, there is no way to pass the parameters to it from program, if required.

9 - 14 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

5. It can only access the static members of the class because non-static members in the
class are specific to the object instance. So static constructor, if allowed to work on
non-static members, will reflect the changes in all the object instances, which is not
possible.
6. There should be no access modifier in static constructor definition because the call to
the static method is made by the CLR and not by the object.

Output

9 - 15 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

5. Order of Finalizersor(destructors) in inheritance hierarchy


Destructor execution follows the opposite approach as that of constructor execution order;
the derived class destructor is called first then the base class. Destructor implicitly calls
Finalize on the base class of object.
Example
System;

Base
{

Output

9.1.7 What is not being Inherited ?

Sealed and abstract classes are never inherited.


Constructor and destructor are never inherited.

9 - 16 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9.1.8 Application of Inheritance

Situation where in inheritance is useful in the application


1. When there are classes that have certain common and certain uncommon properties then
inheritance is handy to encapsulate common features in base class.
2. A new class need the properties of some existing class which provides extension to it.
3. To implement relationships amongst the objects, which are, is-a, is-a-kind, is-a-like.
4. To implement more general class or to implement more specialized class is the main goal
of inheritance. This in turn provides combination of multiple classes.

9.2 Polymorphism and Runtime Behaviours

Concept
1. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the
characteristic of being able to assign a different meaning or application to same statement
or something, in different contexts – programmatically, to allow a variable to refer to
more than one type of object.
Explanation
2. Polymorphism provides following features
It allows to invoke methods of derived class through base class reference during
runtime.
It has the ability for classes to provide different implementations of methods that are
called through the same name.

3. Polymorphism is of two types namely,


1. Compile time polymorphism/Overloading
2. Runtime polymorphism/Overriding

Fig. 9.2.1 Types of polymorphism

9 - 17 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

4. Compile Time Polymorphism (Static polymorphism)


Compile time polymorphism is implemented using method and operator overloading. It is
also termed as early binding.
In method overloading method performs the different task using different input parameters.
5. Runtime Time Polymorphism (Dynamic polymorphism)
C# provides runtime polymorphism through inheritance, overriding and virtual method.
Inheritance-based polymorphism allows to define method in a base class and override it in
derived class with implementation. Thus, if a base class object that can hold derived class
objects, polymorphism, when properly used, allows to call a method that will work differently
according to the type of derived class the object belongs to.
Many times method overriding is called runtime polymorphism. It is also termed as late
binding.
When overriding a method, the behavior of the method is changed for the derived class.
Overloading a method simply involves having another method with the same prototype.
It should be clearly remembered that method overloading and method overriding are
different, unrelated concepts.
Method overloading has nothing to do with inheritance or virtual methods.
6. Method overloading – Why and When
1. Method overloading is used in situation where it is required that a class method
performs some task, but there is more than one possibility for what information is
supplied to the method that carries out the task.
2. Overloading a method should be considered when for some reason there are a couple
of methods that take different parameters, but conceptually do the same thing. OOP
would strongly recommend it as a good programming practice.
3. Keeping the same method name, method overloading can be achieved,
By changing the number of parameters used.
By changing the order of parameters.
By using different data types for the parameters.
4. While doing method overloading there are certain restrictions that the compiler
imposes.
The basic rule is that overloaded methods must be different in their signature,
which means the name and the number and type of parameters. This is necessary for
compiler to distinguish the overloaded methods.

9 - 18 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

There is no limit to how many overloaded methods are there in a class. They are simply
treated as different methods only having same name.
Example

9 - 19 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.3 Overriding Methods

Concept

1. Creating the method in a derived class with same name, same parameters and same return
type as in base class is called as method overriding.
Explanation

2. By method overriding run time polymorphism is achieved.


3. It should be noted that,
Method overriding is only possible in derived class not within the same class
where the method is declared.
Only those methods are overridden in the derived class that have been declared in
the base class with the help of virtual keyword or abstract keyword.
4. ‘virtual’ keyword and ‘override’ keyword.
1. They are both method modifiers.
2. They are used to implement polymorphic behaviour of objects.
3. Virtual method and overriding
1. The virtual keyword is used to create a virtual method and In the derived class
override keyword is used to redefine the method of base class. If the method
in the derived class is preceded with the override keyword, objects of the
derived class will call that method rather than the base class method.
2. A virtual method is a method that can be redefined in the derived class. The
virtual keyword designates a method that is overridden in derived classes. A
virtual method has an implementation in a base class as well as derived the
class.
3. It is used when a method's basic functionality is the same but sometimes more
functionality is needed in the derived class.
4. A virtual method is created in the base class that can be overridden in the
derived class. Virtual method can be created in the base class using the virtual
keyword and that method is overridden in the derived class using the override
keyword.

9 - 20 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

5. When a method is declared as a virtual method in a base class then that


method can be defined in a base class and it is optional for the derived class to
override that method. The overriding method also provides more than one
form for a method. Hence it is a polymorphism.
6. When a method is declared as a virtual method in a base class and that method
has the same definition in a derived class then there is no need to override it in
the derived class. But when a virtual method has a different definition in the
base class and the derived class then there is a need to override it in the
derived class.
7. When a virtual method is invoked, the run-time type of the object is checked
for an overriding member. The overriding member in the derived class is
called, which might be the original member, if no derived class has
overridden the member.
8. One can add derived types without modifying the rest of the program. The
runtime type of objects thus determines behavior.
9. The virtual modifier tells the compiler that when any class is derived from
other class an override method should be called, upon its invocation.
10. By default, methods are non-virtual. One can't override a non-virtual method.
4. One can't use the virtual modifier with the static, abstract, private or override
modifiers.
5. The virtual keyword is used to modify a method, property, indexer, or event declared
in the base class and allows it to be overridden in the derived class.
6. The override keyword is used to extend or modify a virtual/abstract method, property,
indexer, or event of base class into derived class.
7. Difference between virtual and non-virtual methods.
When virtual and non-virtual methods are called by class's instance then according to the
run type the instance virtual method implementation is invoked; in other words in case of
virtual method class's instances invoke the subclass override method and the non-virtual
method invoked is determined based on the instance of the class.
8. Calling virtual method of the base class from derived class which is overridden in
derived class – .
The base class method implementation can be called from derived class method by
using member access operator (.) and the name of the base class.

9 - 21 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

For Example

Example

9 - 22 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

8. Sealed methods
1. A sealed method overrides an inherited virtual method with the same signature.
2. A sealed method shall also be marked with the override modifier.
3. Use of the sealed modifier prevents a derived class from further overriding the
method. The word further is the main aspect here.
4. Idea is that, a method must be virtual in base class. It must be later overridden in
derived class. And at this point, once overridden it is sealed now, disallowing further
overriding.

9 - 23 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9.4 Hiding Method

Concept

1. When a derived class inherits from a base class, the derived class is allowed to define
methods again that are already present in the base class. In such a situation it is said that
base class is hiding the method from derived class.
Explanation

2. To achieve this explicitly it is required to inform the compiler about method hiding, which
is done using ‘new’ keyword. If the ‘new’ keyword is not specified the compiler issues
a warning.

9 - 24 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

3. New keyword is used in polymorphism concept, in the case of method overloading, in


which base class methods are hidden through derived class.
4. The "new" keyword can be is used to hide a method, property, indexer, or event of the
base class into the derived class.
5. If a method is not overriding the derived method then it is hiding it. A hiding method must
be declared using the new keyword.
6. If a method is simply hidden then call to its implementation is based on the compile-time
type of the argument "this". But if a method is overridden then the implementation to be
called is based on the run-time type of the argument "this".
7. New is reference-type specific, overriding is object-type specific.
Example

9 - 25 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.5 Combining Method Overriding and Method Hiding

Concept

Method hiding and method overriding can be used together by using virtual and new
keyword since the method of a derived class can be virtual and new at the same time. This is
required when further overriding of the derived class method is to be disallowed.
using System;

9 - 26 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.6 Operator Overloading

Concept

1. Sometimes there is requirement to add values of objects of those classes to get new
objects or new values. To make the classes well equipped to perform arithmetic
operations or comparisons on their objects, operator overloading can be used.
Explanation

2. Operator overloading consists of customizing the behavior of a C# operator to be able to


apply it on the values of a class. This means that one must create a special behavior in the
class for a particular operator one want to use.
3. Following is the syntax for overloading the operator

First is access level. This is public.


After the public access level, the static keyword used.
Because the method is statically implemented, name of its class should be used as
the return type. Also the operator will act on an object of its class type therefore
the method should return a value that represents its class.

9 - 27 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

After the return type, ‘operator’ keyword is used. This is followed by the actual
operator to be overloaded.
Because a type of method is being created, after the operator, parentheses are added.
In the parentheses, one or two arguments are added, depending on the operator.
Since this is a method implementation, it must have a body delimited by curly
brackets.
After defining the method, it can be called from either inside or outside of its class.
4. There are set of rules that should be followed while overloading operators some which
are mentioned below.
1. Operators must be public and static.
2. One or two formal parameters must occur, corresponding to unary and binary
operators.
3. At least one of the parameters must be of the type to which the operator belongs.
4. Only value parameters can be used.
5. Some operators must be defined in pairs that is either none or both, which are listed
below,
== and != < and > <= and >=
6. The special unary boolean operators and are defined when an object is
playing the role as true or false in relation to the conditional logical operators.
7. Overloading the binary operator op causes automatic overloading of the assignment
operator op=
5. Suggestions and rule of thumb to be followed when overloading operators -
Not all operators need to be customized for all classes. For example, while it would be
feasible to add two books to get a new book that includes all the pages on both books
and their combined authors, it may not be realistic to multiply two books (to get
what?). Therefore, one should select the right operator based on requirements.
While some operators are always available to be overloaded, some operators have
restrictive rules. This means that one cannot just use any operator anyhow.
Not all operators are overloadable.
6. General syntax for overloading unary operator

9 - 28 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

7. General syntax for overloading binary operator

8. Following is the list of operators that can be overloaded

Category Operators Associativity

9 - 29 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9. Some operators either cannot be overloaded or depend on other operators being


overloaded.
The following operators cannot be overloaded : - the conjunction (AND) &&, the
disjunction (OR) ||, the assignment =, the period ., the ternary ?:, the C++ pointer
access ->, the object creator new, the object compatibility verifier is, the size of
sizeof, and the type of typeof
true and false can be overloaded but there is hardly any reason to do it. So, unless
one has a good justified reason, don't overload them
[] cannot be overloaded but the alternative is to create an indexer.
10. Overloading Unary Operators
A unary operator is one that acts on one value.
The C# language provides many unary operators but not all can be overloaded. The
unary operarors available for overloading are +, -, !, ~, ++, and --.
To overload a unary operator, pass one argument to the parentheses of the method. In
the body of the method, perform the desired operation.
11. Binary Arithmetic Operators
A binary operator is one that acts on two values.
The values must be of the same type.
C# provides a rich set of binary operators. Those used in arithmetics are: +, -, *, /, and
%.
To overloaded a binary arithmetic operator, pass two arguments to the parentheses of
the method. The first arguments must be of the type of class in which overloading is
done. The second argument can be another type.
12. Binary Bitwise Operators
Besides the traditional arithmetic operations, C# support the ability to add or shift bits
in the computer memory.
These operators are the bitwise conjunction operator & and its assignment operator
&=, the bitwise disjunction operator | and its assignment operator |=, the bitwise
exclusion operator ^ and its assignment operator ^=, the left-shift operator << and its
assigment operator <<=, the right-shift operator >> and its assignment operator >>=.
When necessary, one should overload only the primary operator (&, |, ^, <<, >>) and
its equivalent assignment operator will be automatically provided by the compiler.
To overloaded a binary operator, pass two arguments to the parentheses of the
method.

9 - 30 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

For the two bitwise shift operators, << and >>, the first argument must be the class in
which one is working and the second argument must by a constant integer (type int).
13. Comparison Operators
As the name implies, a comparison is used to find out whether one of the two values is
higher than the other. The values must be of the same type. Comparison operators work in
pair.
That is, if one wants to compare two values for equality, one must also be able to know
when they are different. For this reason, if a comparison operator is to be overloaded, then
its opposite also needs to be overloaded. That is,
If ‘= =’ is overloaded, ‘!=’ must also be overloaded.
If ‘<’ overloaded, ‘>’ must also be overloaded and vice versa.
If ‘<=’ is overloaded, >= must be overloaded and vice versa.
Example

9 - 31 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Output

9.7 Generics

In C#, generic is a type that is used to define a class, structure, interface or method with
placeholders (type parameters) to indicate that they can store or use one or more of the types.
In C#, the compiler will replace placeholders with the specified type at compile time.
In C#, mostly a generics is used with collections and the methods that operate on them to
specify a type of objects to be stored in a collection. The generics are introduced in .NET
Framework 2.0 with a new namespace called System.Collections.Generic.
Defining A Generic Class

A generic class is defined using angle brackets <>. For example, the following is a simple
generic class with a generic member variable, generic method and property. To define a class
or method as generic, then a type parameter is used as a placeholder with an angle (<>)
brackets.
Below a generic class is defined with type parameter (T) as a placeholder with an angle
(<>) brackets.

9 - 32 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Example 1 Generic Class

In above example, the generic class is created with one parameter (code) and method
(genericMethodShow) using type parameter (T) as placeholder with an angle (<>) brackets.
Here, the angle (<>) brackets will indicate a GenericClass is generic and type parameter
(T) is used to accept a requested type. The type parameter name can be anything like X or U
or etc. based on our requirements.
Generally, while creating an instance of the class it is required to specify an actual type,
then the compiler will replace all the type parameters such as T or U or X, etc. with specified
actual type. In C#, the following is the example of creating an instance of a generic class.
Creating object of generic class (instantiating a generic class)

As seen in the above code, a type "string" is sent to the compiler and it will substitute all
the type parameters (T) with defined type "string" and the defined generic class
(GenericClass) will looks as below after substitution,

In C#, one can create own custom generic types and methods can be defined to provide
own generalized solutions that are type-safe and efficient.

9 - 33 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Example 2 Generic Class

When compiled compiler replaces T with int in GenericClass2 and the compiled code
looks as below,

9 - 34 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Features of Generics

1. It helps to maximize code reuse, type safety, and performance.


2. Generic collection classes can be created. The .NET Framework class library
contains several new generic collection classes in the System.Collections.Generic
namespace. Hence these generic collection classes can be used instead of the
collection classes in the System.Collections namespace.
3. Using generics, generic interfaces, classes, methods, events, and delegates can be
created.
4. Generic classes can be created that can constrained to enable access to methods on
particular data types.
5. The information on the types used in a generic data type can be obtained at run-time
by means of reflection.
Generics can be applied to the following C# entities,

Interface
Abstract class
Class
Method
Static method
Property
Event
Delegates
Operator
Advantages of Generics

1. Increases reusability of the binary code - Generics provide a kind of source code
protection. A Generic class can be defined once and can be instantiated with many
different types. Generics can be defined in one CLR supported language and used from
another .NET language. The following TestClass<T> is instantiated with an int and
string types,

2. Type safe - Significant feature of Generics is Type Safety. Compile time errors are
generated if different type of data is used than the one specified in the definition. In the

9 - 35 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

case of the non-generic ArrayList class, if objects are used, any type can be added to
the collections that can sometimes result in a great disaster. The following example
shows adding an integer, string and object to the collection of an ArrayList type

Now, if the collection is iterated through the foreach statement using integer elements, the
compiler accepts the code but because all the elements in the collection are not an integer, a
runtime exception occurs as seen in below code.

With the definition of Test<int>, only an integer type can be added to the collection. The
compiler doesn't compile the code (generates error) because the Add() method has invalid
arguments as follows;

3. Enhanced Performance - Generic has a performance advantage because it removes


the possibilities of boxing and unboxing. Using value types with non-generic collection
classes result in boxing and unboxing overhead when a value type is converted to
reference type and vice-versa.
In the following example, the ArrayList class stores objects and the Add() method is
defined to store some integer type argument. So an integer type is boxed. When the value from
ArrayList is read using the foreach statement, unboxing occurrs.

Instead of using objects, a Generics type of the TestClass<T> class is defined as an int, so
an int type is used inside the class that is generated dynamically from the compiler. Therefore
boxing and unboxing no longer occurs as in the following;

9 - 36 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

C# Generic Methods

In C#, if a method is defined with type parameter, then it is called a generic method.
Following is the example of defining a generic method with type parameter using angle (<>)
brackets.

This generic method can be called either by specifying the type of argument or without an
argument like as shown below.

Example of generic method

9 - 37 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Generics in inheritance
Generic Class as Base Class

In C# the generic class can used as a base class, but there is need to provide a type instead
of type parameter for the base class because there is no way to send a required type argument
to instantiate a base class at run time. Hence, while deriving from a generic base class, one
must provide a type argument instead of the base-class's generic type parameter as shown
below.

If the derived class is required to be generic then no need to specify type for the generic
base class.
Example : Generic derived class

If the generic base class has constraints, the derived class must use the same
constraints.
Example : Constraints

9 - 38 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

C# Generic Delegates

In C#, a generic delegate will be same as a normal delegate with additional generic type
with angle (<>) brackets.
Following is the example of defining a generic delegate in C# programming language.

Two Marks Questions with Answers

Q.1 What is a base class and derived class ?


Ans. : A class is a template for creating an object. The class from which other classes derive
fundamental functionality is called a base class. For e.g. If Class Y derives from Class X,
then Class X is a base class.

9 - 39 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

The class which derives functionality from a base class is called a derived class. If Class
Y derives from Class X, then Class Y is a derived class.
Q.2 What is inheritance ?
Ans. : Inheritance represents the relationship between two classes where one type derives
functionality from a second type and then extends it by adding new methods, properties,
events, fields and constants.
C# support two types of inheritance :
Implementation inheritance
Interface inheritance
Q.3 What is implementation and interface inheritance ?
Ans. : When a class (type) is derived from another class(type) such that it inherits all the
members of the base type it is Implementation Inheritance.
When a type (class or a struct) inherits only the signatures of the functions from another
type it is Interface Inheritance.
In general Classes can be derived from another class, hence support Implementation
inheritance. At the same time Classes can also be derived from one or more interfaces.
Hence they support Interface inheritance.
Q.4 Define Overriding.
Ans. : Overriding is a concept where a method in a derived class uses the same name, return
type, and arguments as a method in its base class. In other words, if the derived class
contains its own implementation of the method rather than using the method in the base
class, the process is called overriding.
Q.5 Can you use multiple inheritance in .NET ? Why don’t we have multiple
inheritance in .NET ?
Ans. : .NET supports only single inheritance. However the purpose is accomplished using
multiple interfaces.
There are several reasons for this. In simple words, the efforts are more, benefits are
less. Different languages have different implementation requirements of multiple
inheritance. So in order to implement multiple inheritance, we need to study the
implementation aspects of all the languages that are CLR compliant and then implement a
common methodology of implementing it. This is too much of efforts. Moreover multiple
interface inheritance very much covers the benefits that multiple inheritance has.

9 - 40 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Long Answered Questions

Q.1 Define and discuss inheritance by giving example. (Refer section 9.1)
Q.2 How polymorphism is achieved in C# ? (Refer section 9.2)
Q.3 What is the purpose of combining method hiding and method overriding ?
(Refer section 9.5)
Q.4 Discuss operator overloading in C#. (Refer section 9.5)
Q.5 What are generics ? (Refer section 9.7)
Q.6 Write a C# program to demonstrate hierarchical inheritance.
Ans. :

9 - 41 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Q.7 Write a C# Program to Illustrate Multilevel Inheritance with Virtual Methods.

Ans. :

9 - 42 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

Q.8 Write a classTime() which represents time. The class should have three fields
for hours, minutes and seconds. It should have a constructor to initialize the
hours, minutes and seconds and a method printTime() to print the current time.
Overload the following operators :
+ (add two time objects based on 24 hour clock)
< (compare two time objects (Refer section 9.6)

C# - OOP II - Inheritance, Polymorphism and Generics ends …

9 - 43 C# and .NET Programming


C# - OOP II - Inheritance, Polymorphism and Generics

9 - 44 C# and .NET Programming


C# and .NET Framework - Introduction

Syllabus : Delegates Lambdas Lambda Expressions Events, Event Listener Strings


and Regular Expressions

Section No. Topic Name Page No.


10.1 Delegates 10 - 2
10.2 Lambda and Lambda Expression 10 - 6
10.3 Events 10 - 9
10.4 Regular Expressions 10 - 15
Two Marks Questions with Answers 10 - 21
Long Answered Questions 10 - 23

10 - 1 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

10.1 Delegates

Concept

1. The C and C++ languages use concept of function pointer. Callback functions are used in
Microsoft Windows programming to process messages. Because of their functionality,
callback functions were carried out in the .NET Framework but they were defined with
the name of delegate.
Explanation

2. A delegate is a special type of user-defined variable that is declared globally, like a class.
A delegate provides a template for a method, same as an interface provides a template for
a class.
3. But like an interface, a delegate is not defined. Its role is to show what a useful method
would look like. Delegate provides all the necessary information that would be used on a
method. Information can be a return type, no argument or one or more arguments.
4. A delegate is a type the values of which consist of methods.
5. Delegates allow to work with variables and parameters that contain methods .Delegates
can take one or more arguments and arguments can also be passed to the delegate.
6. Creating a Delegate
To create a delegate, delegate keyword is used.
Syntax do declare delegate,

The modifier can be one or an appropriate combination of the following keywords : new,
public, private, protected or internal.
The delegate keyword is required.
The ReturnType can be any of the data types used so far. It can also be a type void or the
name of a class.
The Name must be a valid C# name.
Because a delegate is some type of a template for a method, parentheses are necessary to
use, that are required for every method. If this method will not take any argument,
parentheses are left empty.
7. Accessing a Delegate
After declaring a delegate, it only provides a template for a method, not an actual method.

10 - 2 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

In order to use it, there must be a method defined that would carry an assignment.
That method must have the same return type and the same (number of) argument(s), if
any.
Once a method is assigned to a delegate variable, the delegate variable can be used as if it
were a defined method. That is, it can be called it as a normal method.
With such a method implemented, one can associate it to the name of the delegate. To do
this, one needs to use the method, declare a variable of the type of the delegate and assign
the method to the delegate variable. While assigning the method to a delegate, one of the
rules of delegates is that one must not apply the parentheses to the method.
Example

Output

10 - 3 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

8. A delegate can handle the static method


For using the delegate, one has to declare a variable of the class type before accessing its
method.
An alternative is to create the associated method as static.
In this case there is no need to declare the variable first.

9. Delegate can be anonymous


It is not always required to name the method which a delegate is going to refer. In other
words, there is no need to explicitly define a method prior to using the delegate. Such a
method is referred to as anonymous.
To create an anonymous method, a variable is declared for the delegate and assigned to
the delegate keyword as if it were a method and it is followed by parentheses and curly
brackets that would represent the body of the method, inside which its implementation is
provided.

10 - 4 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

10. A delegate can return a value


Example

Output

10 - 5 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

11. Arguments can be passed to the delegate


To associate the method to the delegate, one can declare a variable for the delegate and
assign the name of the method to it.
Example

Output

10.2 Lambda and Lambda Expression

C# 3.0 (.NET 3.5) introduced the lambda expression along with LINQ. The lambda
expression is a shorter way of representing anonymous method using the provided
syntax.
In Lambda expressions there is no need to specify the type of the value of the input thus
making it more flexible to use.
The ‘=>’ is used in lambda expression which is the lambda declaration operator, to
separate the lambda's parameter list from its executable code. The Lambda expression
is divided into two parts, the left side is the input and the right is the expression.

10 - 6 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

The Lambda Expressions can be of two types

Expression Lambda - Consists of the input and the expression.


Syntax

Statement Lambda - Consists of the input and a set of statements to be executed. This set
of statement is enclosed within the curly brackets.
Syntax

Simple examples are,

Here, Count is the input and count+8 is the expression.

Here, num is the input parameter and num % 2 == 0 is the expression

The result of above code lines is,

Lambda Expression without Parameter

The lambda expression can be specified without any parameter.


Example

10 - 7 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

Lambda Expression with Multiple Parameters

For lambda expression parameters can be sent in the parenthesis.


Example

Declare Local Variable in Lambda Expression Body

A local variable can be declared in the expression body to use it anywhere in the expression
body.
Example

Assign Lambda Expression to Delegate

The lambda expression can be assigned to Func<in T, out TResult> type delegate. The last
parameter type in a Func delegate is the return type and rest are input parameters.
Example

10 - 8 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

10.3 Events

Concept

1. Events are user actions such as key press, clicks, mouse movements, etc. or some
occurrence such as system generated notifications. The event concept is central in event-
driven programming. Programs with graphical user interfaces are event-driven

10 - 9 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

Explanation

2. In command-driven programming, the program asks the user for input and continues the
processing based on it. In event-driven programming the program reacts on what happens
on the elements of the user interface or more generally, what happens on some selected
state of the object and program.
3. Application need to respond to event when event occurs.
For example, interrupts like file not available for writing.
4. Events are used for inter-process communication.
When a given event is triggered the actions that are associated with this particular event
are carried out.
5. Event in C#
1. In C# an event in some class is a variable of a delegate type in that class.
2. As like classes, delegates are also reference types.
3. This implies that an event holds a reference to an instance of a delegate. The memory
for delegate is allocated on the heap.
4. Events are used to provide notifications, typically in relation to graphical user
interfaces.
5. Using Delegates with Events
1. The events are declared and raised in a class and associated with the event
handlers using delegates within the same class or some other class.
2. The class containing the event is used to publish the event. This class is called as
the publisher class.
3. The class that accepts this event is called the subscriber (The Event Listener
and a Event Handler) class.
4. A publisher is an object that contains the definition of the event and the
delegate. The event-delegate association is also defined in this object. A
publisher class object invokes the event and then other objects are notified.
5. A subscriber is an object that accepts the event and provides an event handler
routine. The delegate in the publisher class invokes the method (event handler) of
the subscriber class.
6. Because the publisher and subscriber objects work together, the events are said to
be using the publisher-subscriber model.

10 - 10 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

7. Events are members of the class that raises them. When some thing happens a
class can raise an event, which has a message that contain information about the
event (in the form event arguments) and send them to rest of the program, other
parts of the program can respond to the event by executing the event handler
methods.
8. Event handler method has the same signature as the event and this method is
executed when the event occurs.
9. For defining an event, a two step procedure is followed.
1. A delegate is defined that contains the methods which will be called when the
event is raised.
2. The event based on that delegate is defined.
6. Event - the key points
1. Event Handlers in C# return void (no return type) and take two parameters. The
First parameter of Event - Source of Event means publishing object. The Second
parameter of Event - Object derived from EventArgs.
2. The publishers determine when an event is raised and the subscriber determines
what action is taken in response.
3. An Event can have multiple subscribers. If an Event has multiple subscribers then
event handlers are invoked synchronously. Events will not be raised if there is no
subscriber.
4. All events are based on delegates.
5. Events are basically used for the single user action like button click.
6. An Event is created using event keyword.
7. All the published events must have a listening object.
8. All Events should be defined starting with "On" keyword.
9. Event keyword is used with delegate type to declare an event.
10. Event should be checked if null or not before raising.
11. Event can subscribed using "+=" operator. Event can be unsubscribe using "-="
operator.
12. Function that handles the event is called event handler. Event handler must have
same signature as declared by event delegate.
13. Events can have arguments which will be passed to handler function.
14. Events can also be declared static, virtual, sealed and abstract.

10 - 11 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

15. An Interface can include event as a member.


16. The .NET framework uses an EventHandler delegate and an EventArgs base
class.
Example 1

Output

Example 2

Add/Remove Operation in Events


Below is the example of an Event - System.EventHandler Delegate type

10 - 12 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

Output

Example 3

10 - 13 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

10 - 14 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

When the application is executed, after every 3 seconds Publisher raise an event which is
listened by the Subscribers. And the data Broadcasted by the Publisher can be caught by its
subscribers.
Hello Raj, Message from technical.in at 26-3-2020 08:45:30 New Quiz Is Uploaded!
Hello Ravi, Message from technical.in at 26-3-2020 08:45:30 New Quiz Is Uploaded!
Hello Raj, Message from technical.in at 26-3-2020 08:45:33 New Quiz Is Uploaded!
Hello Ravi, Message from technical.in at 26-3-2020 08:45:33 New Quiz Is Uploaded!
Hello Raj, Message from technical.in at 26-3-2020 08:45:36 New Quiz Is Uploaded!
Hello Ravi, Message from technical.in at 26-3-2020 08:45:36 New Quiz Is Uploaded!

10.4 Regular Expressions

A regular expression is a pattern that could be matched against an input text. The .Net
framework provides a regular expression engine that allows such matching. A pattern consists
of one or more character literals, operators, or constructs.

10 - 15 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

A regular expression is used to check if a string matches a pattern or not. A regular


expression or regex or regexp is a sequence of characters that defines a pattern. The pattern is
used to search strings or files to see if matches are found. Regular expressions are often used
in input validations, parsing, and finding strings. For example, checking a valid date of birth,
social security number, full name where the first and the last names are separated by a comma,
finding number of occurrences of a substring, replacing substrings, date formats, valid email
formats, a currency format etc. They are a powerful way to find and replace strings that take a
defined format.
10.4.1 Regular Expression Syntax and Quantifiers
Various quantifiers are used in association with other characters create represent regular
expression.
Following are various quantifiers allowable in regular expression.
Most widely used quantifiers are *, ?, +.
1. Quantifier * matches the preceding character zero or more times.
Example
Regular expression a*b
Above regular expression matches below strings,
b, ab, aab, aaab, aaaab,…that is a string containing n number of a's followed by single b
where n > = 0 .
2. Quantifier + matches the preceding character zero or more times.
Example,
Regular expression a+b
Above regular expression matches below strings,
ab, aab, aaab, aaaab, aaaaab,…that is a string containing n number of a's followed by single
b where n > 0.
3. Quantifier ? matches the preceding char zero or one time.
Example
Regular expression a?b
Above regular expression matches below strings,
b, ab, that is only single character before ? is matched.
10.4.2 Special Characters as Quantifiers

Many special characters are available for regex building. Below are some of them used
frequently.

10 - 16 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

1. ^ It is used to match the beginning of a string.


Example
^Ram matches 'Ram is a good boy'
2. $ It is used to match the end of a string.
Example
Ram$ matches 'Have you been to Ram'
3. . (Dot) Matches any character only once.
Example
p.n matches 3 letter words like pan,pen,pin,p!n
4. \d It is used to match a digit character.
Example
[0-9]
5. \D It is used to match any non-digit character.
Example
[^0-9]
6. \w It is used to match an alphanumeric character plus "_".
Example
A to Z
0 to 9
A to z, _
7. \W It is used to match any non-word character.
Example
@ in 'meet@parking'
8. \s Matches white space characters.
Example
\w\s matches A in "PA K93"
9. \S Matches a non-white space character.
Example
\s\S matches '_' in "Hello_ALL"
10. \n Matches a newline character.

10 - 17 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

10.4.3 Character Classes

Characters can be grouped together by putting them between square brackets. This way,
any character in the class will match one character in the input.
[ ] It is used to match a range of characters.
Example

[mnp] matches any of the m or n or p letter.


[a-z] matches range, any character from a to z.
[^def] a ^(caret) at the beginning indicates do not match, that is match
anything other than d or e or f.
B[aei]L will match for BaL, BeL, BiL
Grouping and alternatives

It's often necessary to group things together with parentheses.


1. () It is used to group expressions.
Example
(jk)+ matches jk, jkjk, jkjkjk
(ab | xy) matches ab, xyab Here, the | operator is the Or operator that
takes any of the alternatives.
2. {} It is used to match the preceding character for a specified number of times.
{n} matches the previous element exactly n times.
Example
@\d{3} matches @123, @5@3, @345 @thr
in string "Hi@1234@5@345werf@thr34"
{n,m} Matches the previous element at least n times, but no more than m times.

Example
"\d{2,4} matches 67, 7689
10.4.4 The Regex Class

In .NET, the Regex class represents the regular expression engine. It can be used to
quickly parse large amounts of text to find specific character patterns; to extract, edit, replace,
or delete text substrings; and to add the extracted strings to a collection to generate a report.
The Regex class is defined in the System.Text.RegularExpressions namespace. The Regex
class constructor takes a pattern string as a parameter with other optional parameters.

10 - 18 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

It has the following commonly used methods,


Methods and Description

1. public bool IsMatch(string input) : Indicates whether the regular expression


specified in the Regex constructor finds a match in a specified input string.
2. public bool IsMatch(string input, int startat) : Indicates whether the regular
expression specified in the Regex constructor finds a match in the specified input
string, beginning at the specified starting position in the string.
3. public static bool IsMatch(string input, string pattern) : Indicates whether the
specified regular expression finds a match in the specified input string.
4. public MatchCollection Matches(string input) : Searches the specified input string
for all occurrences of a regular expression.
5. public string Replace(string input, string replacement) : In a specified input
string, replaces all strings that match a regular expression pattern with a specified
replacement string.
6. public string[] Split(string input) : Splits an input string into an array of substrings
at the positions defined by a regular expression pattern specified in the Regex
constructor.
Using Regex class

The following code snippet creates a Regex from a pattern. Here pattern is to match a word
starting with char ‘M’.

Program to demonstrate use Refex class


1. Program to match the pattern

10 - 19 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

2. Program to replace multiple white spaces using Regex. The following example uses
the regular expression pattern [a-z]+ and the Regex.Split() method to split a string on
any uppercase or lowercase alphabetic character.

3. To use regex for email validation


For validating multiple emails, following regular expressions can be used. Emails are
separated by using delimiter ';'
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;]{0,1}\s*)+$
To use delimiter ',' below pattern would be used,
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[,]{0,1}\s*)+$
and to use both delimiter ',' and ';' then below can be used,
^((\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;,.]{0,1}\s*)+$

10 - 20 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

4. To replace special characters from string using regex


If there is a string with special characters and there is need to remove/replace those
characters, then regex can be used,
Regex.Replace(Stringwithchars, @"[^0-9a-zA-Z]+", "")
This code will remove all of the special characters but there is no need to remove some of
the characters like “,” and “:” then below regex can be used,
Regex.Replace(Stringwithchars, @"[^0-9a-zA-Z:,]+", "")

Two Marks Questions with Answers

Q.1 What are events and delegates ?


Ans. : An event is a message sent by a control to notify the occurrence of an action.
However it is not known which object receives the event. For this reason, .NET provides a
special type called Delegate which acts as an intermediary between the sender object and
receiver object.
Q.2 What is a Delegate ? Explain.
Ans. : A Delegate is a variable that holds the reference to a method. Hence it is a function
pointer or reference type. All Delegates are derived from System.Delegate namespace.
Both Delegate and the method that it refers to can have the same signature.
Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created by the delegate using the
new keyword.

The delegate provides a kind of encapsulation to the reference method, which will
internally get called when a delegate is called.
Q.3 What are Regular expressions? Search a string using regular expressions ?
Ans. : Regular expression is a template to match a set of input. The pattern can consist of
operators, constructs or character literals. Regex is used for string parsing and replacing the
character string.
For Example :

10 - 21 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

The above example searches for "Python" against the set of inputs from the languages
array. It uses Regex.IsMatch which returns true in case if the pattern is found in the input.
The pattern can be any regular expression representing the input that we want to match.
Q.4 What are Events ?
Ans. : Events are user actions that generate notifications to the application to which it must
respond. The user actions can be mouse movements, keypress and so on.
Programmatically, a class that raises an event is called a publisher and a class which
responds/receives the event is called a subscriber. Event should have at least one subscriber
else that event is never raised.
Delegates are used to declare Events.
Public delegate void PrintNumbers();
Event PrintNumbers myEvent;
Q.5 What are the different types of Delegates ?
Ans. : Different types of Delegates are :
Single Delegate : A delegate that can call a single method.
Multicast Delegate : A delegate that can call multiple methods. + and - operators are
used to subscribe and unsubscribe respectively.
Generic Delegate : It does not require an instance of the delegate to be defined. It is
of three types, Action, Funcs and Predicate.
Action : In the above example of delegates and events, we can replace the definition
of delegate and event using Action keyword. The Action delegate defines a method
that can be called on arguments but does not return a result

Action implicitly refers to a delegate.


Func - A Func delegate defines a method that can be called on arguments and returns a
result.
Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);

10 - 22 C# and .NET Programming


C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions

Predicate - Defines a method that can be called on arguments and always returns the bool.
Predicate<string> myDel is same as delegate bool myDel(string s);

Long Answered Questions

Q.1 Discuss the delegates in C#. (Refer section 10.1)


Q.2 What are lambda expressions in C# ? (Refer section 10.2)
Q.3 Discuss the use and applications of lambda expression in C#.
(Refer section 10.2)
Q.4 Discuss Publisher-Subscriber model of events in C#. (Refer section 10.3)
Q.5 How events are handled in C# ? (Refer section 10.3)
Q.6 Write a C# program to convert feet to inches using delegates.

Ans. :

C# Advance Features I - Delegates, Lambdas, Events and Regular Expressions ends …

10 - 23 C# and .NET Programming

You might also like