C# Unit 1
C# Unit 1
Concept
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.
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.
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.
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.
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.
Concept
C# Family
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.
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
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.
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
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.
Concept
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 -
2. Object
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
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. 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
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
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.
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.
Managed code is managed by CLR Any code that is not managed by CLR
CLR manages memory management through Own runtime environment for compilation and
garbage collection execution
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
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.
2.5 Identifier 2 - 15
2.8 Variable 2 - 25
2.12 Comment in C# 2 - 38
2.13 Errors in C# 2 - 39
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
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
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
Fig. 2.2.1
Example
In the above program following are the various Tokens (along with their classification),
Token Classification
2.3 Keyword
Concept
1. Keywords are the language specific, reserved and predefined words that cannot be used as
the identifiers.
Explanation
Do is sizeof while
Yield
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.
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,
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. 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
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
Output
5. String Literals
Output
/*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
Output
6. Null Literals
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,
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
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
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).
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.
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.
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.
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').
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.
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.
11. Do not suffix enum names with Enum which is consistent with prior rule of no type
indicators in identifiers.
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.
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
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
2.8 Variable
Concept
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
Example
But following is not a valid statement and would generate compile-time error:
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.
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
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.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
1. Type conversion is a way or method to convert one data type into another data type.
Explanation
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
Output
In this example ToString method is used in order to convert float value into string. It is a
built-in type conversion method.
Listed below are various type conversion methods which are widely used in C#.
Method Description
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.
ToSingle This method converts a data type to small floating point number.
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.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
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
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
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.
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
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.
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}.
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.
3. Types of comment -
The are following types of comments in C#
Single line comments
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 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
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.
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 :
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
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
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.
3.5 Expression 3 - 16
3.1 Operators
Concept
1. Based on the operands involved, method of manipulation, the result of the operation , the
operators are classified in various categories.
Explanation
Relational Operators Used for the comparison between two variables or constants.
1. Arithmetic Operators are the simplest operators used for the purpose of mathematical
operation like addition, subtraction etc.
Explanation
Example
Output
1. Relation operators are used for the relative comparison between two values.
Explanation
== Is equal to 5= = 12 is false.
Example
Output
Operand !Operand
true false
false true
Output
& (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
Output
= (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.
=(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.
%= (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
Output
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
(type) Type conversion operator) This operator is used to convert one data type to
another data type.
Example
Output
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 { }
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
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
*/ %
+-
<< >>
== !=
&
&&
||
:?
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 %
Additive Operators
Left to Right
+ and -
Shift Operators
Left to Right
<<, >>
Equality Operators
Left to Right
== and !=
Bitwise OR 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.
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.
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
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.
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.
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
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
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.
4. unchecked (expression)
5. The expression to be evaluated in an unchecked context. Notice that the expression must
be in parentheses ( ).
Example
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
==, !=, <, >, <=, >= The comparison operators can be overloaded.
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. :
Concept
Control statements are used as additional means to control the processing within the
applications developed.
Explanation
Control Statements Description
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.
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
1. It allows the user to execute different path of logic on the basis of a given condition.
Explanation
6. If statement Syntax
Example
Output
1. If..else statement contains the two blocks if block and else block.
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
Example
Output
Example
Output
A nested if statement contains various structures like if..else statement inside if, if
statement inside else etc.
Example
Output
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
Output
1. When switch-case statements are used inside another switch case statement that is known
as nested switch case statement.
Explanation
Example
Output
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
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
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
Output
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
Example
Output
1. Foreach each loop is used to iterate the elements present in arrays and collections.
Explanation
6. In the above syntax statement, type variable shows the iterative elements and expression
is the name of array.
Example
using System;
Output
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.
5. Nested loop can have various structures based on which loop is being nested inside
another loop.
Example
Output
Concept
1. Jump statement enables user to jump to another section of code either conditionally or
unconditionally.
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
Example
Output
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
Example
Output
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
Example
Output
1. The block statement is used to group multiple segments of program which are logical
related.
Explanation
Example
Ouput
1. Empty statement is used when there is no need to perform an operation where generally a
statement is required.
Explanation
3. It is handy with while loop having blank body and label statements.
4. Empty statement syntax
Example
Output
2. The using statement obtains one or various resources, executes them and then releases the
objects or resources.
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
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.
>>= 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.
Ans. :
Q.7 Write a C# program to Get a Number and Display the Number in its Reverse
order.
Ans. :
Ans. :
Core C# - Part III - Flow Control and Various Control Statements ends …
5.1 Methods
Concept
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
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
Output
Example
Output
1. There are three ways that parameters can be passed to a method while calling the
method.
Explanation
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.
Example
Output
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 :
9. Method scope
Concept
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
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.
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
Output
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.
Example
Output
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.
Example
Output
Concept
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
Output
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. :
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)
6.1 C# Arrays
6.1.1 Concept
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
Value can be assigned to the elements of array at the time of declaration or creation of
array.
Output
Output
Concept
An array which contains only one dimension ( 1 row) is known as one dimensional array.
Explanation
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.
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
Output
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
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,
Example
Output
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
Output
Output
Concept
In C# array is treated as object and inherited from the Array class. Array class is defined in
the System namespace.
Explanation
Example
Output
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.
Example
Output
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
Concept
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.
IsFixedSize Gets a boolean value indicating whether the ArrayList has a fixed size.
When the above code is compiled and executed, it produces the following result :
Concept
The String class in C# represents a string which holds collection of characters or text as a
series of Unicode characters.
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
Example
When the above code is compiled and executed, it produces the following result :
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
Example
Output
Example
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.
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 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.
Output
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.
Names can be assigned to ValueTuple properties instead of having the default property
names Item1, Item2 and so on.
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.
Different member names can be specified for a ValueTuple returned from a method.
Deconstruction
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.
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)
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
Output
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.
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;
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
For 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.
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.
Example
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
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
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
Example
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.
Example
double 0.0D
float 0.0F
int 0
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.
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
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.5 C# provide five access specifiers , namely, public, private , protected , internal and
protected internal.
2.5.1 public
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
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.
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
Output
Output
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
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
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
3. Destructor
Concept
1. A destructor is class member method that runs after a class becomes unreachable.
Explanation
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
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.
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
abstract class, then, in the derived class, it is optional to implement the abstract method(s)
of the base/super class.
Example
Example
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
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
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.
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.1.5 Indexer
Concept
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
Example
Concept
1. Overloading methods in a class means one can define multiple methods that have the
same name but contain different signatures.
Explanation
Example
Example
Concept
1. The variable or fields, declared as const or readonly are called constants whose value
can't be changed.
Explanation
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.
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
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.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.
Output
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
3. It describes all the methods, properties, etc An object is used to access all those
properties from the class.
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
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)
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.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)
Syllabus : Inheritance-Generics.
9.7 Generics 9 - 32
9.1 Inheritance
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)
In single inheritance as the name implies one single class (derived) derives another existing
class (base).
Example
Output
In this inheritance the level of inheritance increases and one class derives another class
which in turn is derived from some other class.
Example
Output
In this type inheritance more than one classes have been derived from single base class
yielding hierarchy like structure.
Example
Output
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.
Output
public accessible
protected accessible
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.
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
Output
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.
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.
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.
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
Base
{
Output
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.
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
Output
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
For Example
Example
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.
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.
Output
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;
Output
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
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
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
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.
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.
When compiled compiler replaces T with int in GenericClass2 and the compiled code
looks as below,
Features of Generics
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
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;
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;
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.
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
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.
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.
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. :
Ans. :
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)
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.
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
Output
Output
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.
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
A local variable can be declared in the expression body to use it anywhere in the expression
body.
Example
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.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
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.
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.
Output
Example 2
Output
Example 3
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!
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.
Many special characters are available for regex building. Below are some of them used
frequently.
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
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.
The following code snippet creates a Regex from a pattern. Here pattern is to match a word
starting with char ‘M’.
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.
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 :
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
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);
Ans. :