Introduction To C#
Introduction To C#
Introduction To C#
It was developed by Microsoft within its .NET initiative and later approved as a
standard by European Computer Manufactures Association (ECMA-334) and
International Organization for Standardization/ International Electrotechnical
Commison(ISO/IEC 23270:2006).
The most recent version is C# 9.0, which was released in November 10 2020 along
with Visual Studio 2019 version 16.8 and .Net Framework version 5.0.
History of C#
During the development of the .NET Framework, the class libraries were originally
written using a managed code compiler system called Simple Managed C (SMC).
In January 1999, Anders Hejlsberg formed a team to build a new language at the time
called Cool, which stood for "C-like Object Oriented Language".
Microsoft had considered keeping the name "Cool" as the final name of the language,
but chose not to do so for trademark reasons. By the time the .NET project was publicly
announced at the July 2000 Professional Developers Conference, the language had
been renamed C#, and the class libraries and ASP.NET runtime had been ported to
C#.
Hejlsberg is C#'s principal designer and lead architect at Microsoft, and was previously
involved with the design of Turbo Pascal, Embarcadero Delphi (formerly CodeGear
Delphi, Inprise Delphi and Borland Delphi), and Visual J++.
In interviews and technical papers he has stated that flaws in most major programming
languages (e.g. C++, Java, Delphi, and Smalltalk) drove the fundamentals of the
Common Language Runtime (CLR), which, in turn, drove the design of the C#
language itself.
Microsoft first used the name C# in 1988 for a variant of the C language designed for
incremental compilation. That project was not completed but the name lives on.
Why C#
C# is pronounced as "C-Sharp". It is an object-oriented programming language
provided by Microsoft that runs on .Net Framework.
✓ Console Applications.
✓ Window applications.
✓ Web applications.
✓ Developing windows controls.
✓ Creating web controls.
✓ Distributed applications.
✓ Web service applications.
✓ Database applications etc.
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework. C# is designed for Common Language Infrastructure (CLI), which
consists of the executable code and runtime environment that allows use of various
high-level languages on different computer platforms and architectures.
Characteristics of C#
The main design goal of C# was simplicity rather than pure power. C# fulfils the need
for a language that is easy to write, read and maintain and also provides the power
and flexibility of C++. The language that is designed for both computing and
communications is characterized by several key features.
It is
✓ Simple
✓ Object-oriented
✓ Compatible
✓ Consistent
✓ Type-safe
✓ Interoperable and
✓ Modern
✓ Versionable
✓ Flexible
Simple
C# simplifies C++ by eliminating irksome operators such as ->,:: and pointers. C#
treats integer and Boolean data types as two entirely different types. This means that
the use of = in place of = = in If statements will be caught by the compiler.
Consistent
C# supports an unified type system which eliminates the problem of varying ranges of
integer types. All types are treated as objects and developers can extend the type
system simply and easily.
Modern
Object-Oriented
Type-safe
Versionable
Making new versions of software modules work with the existing applications is known
as versioning. C# provides support for versioning with the help of new and override
keywords. With this support, a programmer can guarantee that his new class library
will maintain binary compatibility with the existing client applications.
Flexible
Although C# does not support pointers, we may declare certain classes and methods
as 'unsafe' and then use pointers to manipulate them. However, these codes will not
be type-safe.
Inter-operability
C# provides support for using COM objects, no matter what language was used to
author them. C# also supports a special feature that enables a program to call out any
native API.
As stated earlier. C# was derived from C++ to make it the language of choice for C
and C++ programmers. C#, therefore, shares major parts of syntax with C++.
However, the C# designers introduced a few changes in the syntax of C++ and
removed a few features primarily to reduce the common pitfalls that occurred in C++
program development. They also added a number of additional features to make C#
a type-safe and web-enabled language.
Changes Introduced
✓ C# compiles straight from source code to executable code, with no object files.
✓ C# does not separate class definition from implementation. Classes are defined
and implemented in the same place and therefore there is no need for header
files.
✓ C# does not support #include statement. (Note that using is not the same as
#include). All data types in C# are inherited from the object superclass and
therefore they are objects.
✓ All the basic value types will have the same size on any system. This is not the
case in C or C++. Thus C# is more suitable for writing distributed applications.
✓ In C#, data types belong to either value types or reference types.
✓ C# checks for uninitialized variables and gives error messages at compile time.
In C++, an uninitialized variable goes undetected thus resulting in unpredictable
output.
✓ In C#, structs are value types.
✓ C# supports a native string type. Manipulation of strings is easy.
✓ C# supports a native Boolean data type and bool-type data cannot be implicitly
or explicitly cast to any data type except object.
✓ C# declares null as a keyword and considers it as an intrinsic value.
✓ C# does not support pointer types for manipulating data. However, they are
used in what is known as 'unsafe' code.
✓ Variable scope rules in C# are more restrictive. In C#, duplicating the same
name within a routine is illegal, even if it is in a separate code block.
✓ C# permits declaration of variables between goto and label.
✓ We can only create objects in C# using the new keyword.
✓ Arrays are classes in C# and therefore they have built-in functionality for
operations such as sorting, searching, and reversing.
✓ Arrays in C# are declared differently and behave very differently compared to
C++ arrays.
✓ C# provides special syntax to initialize arrays efficiently.
✓ Arrays in C# are always reference types rather than value types, as they are in
C++ and therefore stored in a heap.
✓ In C#, expressions in if and while statements must resolve to a bool value.
Accidental use of the assignment operator (=) instead of equality operator = =
will be caught by the compiler.
✓ C# supports four iteration statements rather than three in C++ . The fourth one
is the foreach statement.
✓ C# does not allow silent fall-through in switch statements. It requires an explicit
jump statement at the end of each case statement.
✓ In C#, switch can also be used on string values.
✓ The set of operators that can be overloaded in C# is smaller compared to C++.
✓ C# can check overflow of arithmetic operations and conversions using checked
and unchecked keywords.
✓ C# does not support default arguments.
✓ Variable method parameters are handled differently in C#.
✓ In exception-handling, unlike in C++, we cannot throw any type in C#. The
thrown value has to be a reference to a derived class or System.Exception
object.
✓ C# requires ordering of catch blocks correctly.
✓ General catch statement catch (...) in C++ is replaced by simple catch in C#
✓ C# does not provide any defaults for constructors.
✓ Destructors in C# behave differently than in C++.
✓ In C#, we cannot access static members via an object, as we can in C++.
✓ C# does not support multiple code inheritance.
✓ Casting in C# is much safer than in C++.
✓ When overriding a virtual method, we must use the override keyword.
✓ Abstract methods in C# are similar to virtual functions in C++, but C# abstract
methods cannot have implementations.
✓ Command-line parameters array behave differently in C# as compared to C++.
Like C#, Java was also derived from C++ and therefore they have similar roots.
Moreover, C# was developed by Microsoft as an alternative to Java for web
programming. C# has borrowed many good features from Java, which has already
become a popular Internet language. However, there exist a number of differences
between C# and Java:
✓ Although C# uses .NET runtime that is similar to Java runtime, the C# compiler
produces an executable code.
✓ C# has more primitive data types.
✓ Unlike Java, all C# data types are objects.
✓ Arrays are declared differently in C#.
✓ Although C# classes are quite similar to Java classes, there are a few important
differences relating to constants, base classes and constructors, static
constructors, versioning, accessibility of members etc.
✓ Java uses static final to declare a class constant while C# uses const.
✓ The convention for Java is to put one public class in each file and in fact, some
compilers require this. C# allows any source file arrangement.
✓ C# supports the struct type and Java does not.
✓ Java does not provide for operator overloading.
✓ In Java, class members are virtual by default and a method having the same
name in a derived class overrides the base class member. In C#, the base
member is required to have the virtual keyword and the derived member is
required to use the override keyword.
✓ The new modifier used for class members has no complement in Java.
✓ C# provides better versioning support than Java.
✓ C# provides static constructors for initialization.
✓ C# provides built-in delegates and events. Java uses interfaces and inner
classes to achieve a similar result.
✓ In Java, parameters are always passed by value. C# allows parameters to be
passed by reference by using the ref keyword.
✓ C# adds internal, a new accessibility modifier. Members with internal
accessibility can be accessed from other classes within the same project, but
not from outside the project.
✓ C# includes native support for properties, Java does not.
✓ Java does not directly support enumerations.
✓ Java does not have any equivalent to C# indexers.
✓ Both Java and C# support interfaces. But, C# does not allow type definitions in
interfaces, while Java interfaces can have const type data.
✓ In Java, the switch statement can have only integer expression, while C#
supports either an integer or string expressions.
✓ C# does not allow free fall_through from case to case.
✓ C# provides a fourth type of iteration statement, foreach for quick and easy
iterations over collections and array type data.
✓ Catch blocks should be ordered correctly in C#.
✓ C# checks overflows using checked statements.
✓ C# uses is operator instead of instanceof operator in Java.
✓ C# allows a variable number of parameters using the params keyword.
✓ There is no labeled break statement in C#. The goto is used to achieve this.
The .Net framework consists of an enormous library of codes used by the client
languages such as C#. Following is some of the components of the .Net framework −
✓ Common Language Runtime (CLR)
✓ The .Net Framework Class Library
✓ Common Language Specification
✓ Common Type System
✓ Metadata and Assemblies
✓ Windows Forms
✓ ASP.Net and ASP.Net AJAX
✓ ADO.Net
✓ Windows Workflow Foundation (WF)
✓ Windows Presentation Foundation
✓ Windows Communication Foundation (WCF)
✓ LINQ
The Common Language Runtime (CLR) is programming that manages the execution
of programs written in any of several supported languages, allowing them to share
common object-oriented classes written in any of the languages. It is a part of
Microsoft's .NET Framework. Microsoft refers to its CLR as a "managed execution
environment." A program compiled for the CLR does not need a language-specific
execution environment and can easily be moved to and run on any system with
Windows 2000 or Windows XP.
Programmers writing in Visual Basic, Visual C++, or C# compile their programs into
an intermediate form of code called Common Intermediate Language (CIL) in a
portable execution file that can then be managed and executed by the CLR. The
programmer and the environment specify descriptive information about the program
when it is compiled and the information is stored with the compiled program as
metadata. Metadata, stored in the compiled program, tells the CLR what language
was used, its version and what class libraries will be needed by the program. The CLR
allows an instance of a class written in one language to call a method of a class written
in another language. It also provides garbage collecting (returning unneeded memory
to the computer), exception handling and debugging services.
Base Class Library Support: It is a class library that provides support of classes to
the .NET application.
COM Marshaler: It provides communication between the COM objects and the
application.
Type Checker: It checks types used in the application and verifies that they match to
the standards provided by the CLR.
Following is the commonly used namespaces that contains useful classes and
interfaces and defined in Framework Class Library.
Namespaces Description
System.Web, System.WebCaching,
System.Web.UI, System.Web.UI.Design,
System.Web.UI.WebControls, These are used to create ASP.
System.Web.UI.HtmlControls, NET Web applications that run
System.Web.Configuration, over the web.
System.Web.Hosting, System.Web.Mail,
System.Web.SessionState
System.Web.Services,
These are used to create XML
System.Web.Services.Description,
Web services and components
System.Web.Services.Configuration,
that can be published over the
System.Web.Services.Discovery,
web.
System.Web.Services.Protocols
System.Xml, System.Xml.Schema,
These namespaces are used to
System.Xml.Serialization, System.Xml.XPath,
create and access XML files.
System.Xml.Xsl
.NET Base Class Library is the sub part of the Framework that provides library
support to Common Language Runtime to work properly. It includes the System
namespace and core types of the .NET framework.
Common Language Specification
Most of the members defined by types in the .NET Framework class library are able
to work with CLS. However, some types in the class library have one or more members
that are not able to work with CLS. These members allow support for language
features that are not in the CLS.
The CLS was designed to be large enough to include the language constructs that are
commonly needed by developers, yet small enough that most languages are able to
support it. Any language construct that makes it impossible to quickly confirm the type
safety of code was excluded from the CLS so that all languages that can work with
CLS can produce verifiable code if they choose to do so.
1. Value Types: Contain the values that need to be stored directly on the stack or
allocated inline in a structure. They can be built-in (standard primitive types),
user-defined (defined in source code) or enumerations (sets of enumerated
values that are represented by labels but stored as a numeric type).
2. Reference Types: Store a reference to the value‘s memory address and are
allocated on the heap. Reference types can be any of the pointer types,
interface types or self-describing types (arrays and class types such as user-
defined classes, boxed value types and delegates).
Although operations on variables of a value type do not affect any other variable,
operations on variables of a reference type can affect the same object referred to by
another variable. When references are made within the scope of an assembly, two
types with the same name but in different assemblies are defined as two distinct types,
whereas when using namespaces, the run time recognizes the full name of each type
(such as System.Object, System.String, etc.). The rich set of types in CTS has well-
designed semantics such that they can be widely used as a base type in Common
Language Runtime (CLR) -based languages.
C# Version History
C# was first introduced with .NET Framework 1.0 in the year 2002 and evolved much
since then. The following table lists important features introduced in each version of
C#:
WinForms
Windows Forms is a smart client technology for the .NET Framework, a set of
managed libraries that simplify common application tasks such as reading and writing
to the file system.
ASP.NET
ASP.NET is a web framework designed and developed by Microsoft. It is used to
develop websites, web applications, and web services. It provides a fantastic
integration of HTML, CSS, and JavaScript. It was first released in January 2002.
ADO.NET
ADO.NET is a module of .Net Framework, which is used to establish a connection
between application and data sources. Data sources can be such as SQL Server and
XML. ADO .NET consists of classes that can be used to connect, retrieve, insert, and
delete data.
WF (Workflow Foundation)
Windows Workflow Foundation (WF) is a Microsoft technology that provides an API,
an in-process workflow engine, and a rehostable designer to implement long-running
processes as workflows within .NET applications.
Entity Framework
It is an ORM based open-source framework which is used to work with a database
using .NET objects. It eliminates a lot of developer’s effort to handle the database. It
is Microsoft's recommended technology to deal with the database.
OVERVIEW OF C#
17-06-2021 II MCA
Overview of C#
2
Every C# executable program must include the Main( ) method in one of the classes.
This is the 'starting point' for executing the program.
A C# application can have any number of classes but 'only one' class can have the
Main method to initiate the execution.
Main() contains a number of keywords: public, static and void.
public : The keyword public is an access modifier that tells the C# compiler that the
Main method is accessible by anyone
static: The keyword static declares that the Main method is a global one and can be
called without creating an instance of the class. The compiler stores the address of
the method as the entry point and uses this information to begin execution before
any objects are created.
void: The keyword void is a type modifier that states that the Main method does not
return any value.
4
Creating and Running C# Program
5
Generally, the programs created using programming languages like C, C++, Java,C#
etc., are written using a high-level language like English. But, the computer cannot
understand the high-level language. It can understand only low-level language. So, the
program written in the high-level language needs to be converted into the low-level
language to make it understandable for the computer. This conversion is performed
using either Interpreter or Compiler.
Popular programming languages like C, C++, Java,C# etc., use the compiler to convert
high-level language instructions into low-level language instructions.
A compiler is a program that converts high-level language instructions into low-level
language instructions. Generally, the compiler performs two things, first it verifies the
program errors, if errors are found, it returns a list of errors otherwise it converts the
complete code into the low-level language.
Stages of Compilation
6
Namespace
7
C# program is a collection of instructions and every instruction is a collection of some individual units.
Every smallest individual unit of a C# program is called tokens. Tokens are used to construct C#
programs and they are said to the basic building blocks of a C# program.
In a C# program tokens may contain the following...
Keywords
Identifiers
Operators
Punctuators
Special Symbols
Constants or Literals
Strings
Data values
In a C# program, a collection of all the keywords, identifiers, operators, special symbols,
constants, strings, and data values are called tokens.
C# Keywords
19
Properties of Keywords
All the keywords in C# programming language are defined as lowercase
letters so they must be used only in lowercase letters
Every keyword has a specific meaning, users can not change that meaning.
21
C# Identifiers
22
The following are the commonly used rules for creating identifiers for
better programming...
The identifier must be meaningful to describe the entity.
Floating-point data types are a set of numbers with the decimal value. Every
floating-point value must contain the decimal value. The floating-point data type
has two variants...
Float
Double
Decimal
We use the keyword "float" to represent floating-point data type and "double"
to represent double data type in c. Both float and double are similar but they
differ in the number of decimal places. The float value contains 6 decimal places
whereas double value contains 15 or 19 decimal places. The following table
provides complete details about floating-point data types.
35
Character Data Type
36
The character data type is a set of characters enclosed in single quotations. The
following table provides complete details about the character data type.
37
By default, the associated constant values of enum members are of type int;
they start with zero and increase by one following the definition text order.
It is possible that we can explicitly specify any other integral numeric type as
an underlying type of an enumeration type.
We can also explicitly specify the associated constant values, as the following
example shows:
enum ErrorCode : ushort
{
None = 0,
Unknown = 1,
ConnectionLost = 100,
OutlierReading = 200
}
Reference types
40
Variables of reference types store references to their data (objects), With reference types, two
variables can reference the same object; therefore, operations on one variable can affect the
object referenced by the other variable. With value types, each variable has its own copy of the
data, and it is not possible for operations on one variable to affect the other.
The following keywords are used to declare reference types:
Class
Interface
Delegate
Record
C# also provides the following built-in reference types:
Dynamic
Object
String
Object
41
Variables in a C# Programming are the named memory locations where the user can store
different values of the same datatype during the program execution. In other words, a variable
can be defined as a storage container to hold values of the same datatype during the program
execution.
The formal definition of a variable is as follows...
Variable is a name given to a memory location where we can store different values of the
same datatype during the program execution.
Every variable in C# Programming must be declared before it is used. Every variable must have
a datatype that determines the range and type of values be stored and the size of the memory
to be allocated.
A variable name may contain letters, digits and underscore symbol. The following are the rules
to specify a variable name...
Variable name should not start with a digit.
Keywords should not be used as variable names.
A variable name should not contain any special symbols except underscore(_).
A variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
43
Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of
memory with the specified variable name and allows only specified datatype
values into that memory location. In C# Programming, the declaration can be
performed either before the function as global variables or inside any block or
function. But it must be at the beginning of block or function.
Declaration Syntax:
datatype variableName;
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory
with the name number and allows only integer values into that memory location.
Constants or Literals
44
A floating-point constant must contain both integer and decimal parts. Some times it may also
contain the exponent part.
The default value of each floating-point type is zero, 0.
Each of the floating-point types has the MinValue and MaxValue constants that provide the
minimum and maximum finite value of that type.
The float and double types also provide constants that represent not-a-number and infinity values.
For example, the double type provides the following constants: Double.NaN,
Double.NegativeInfinity, and Double.PositiveInfinity.
The type of a real literal is determined by its suffix as follows:
The literal without suffix or with the d or D suffix is of type double
The literal with the f or F suffix is of type float
The literal with the m or M suffix is of type decimal
48
This displays "True" and then "False" because the content of the strings
are equivalent, but a and b do not refer to the same string instance.
The + operator concatenates strings:
eg:
The arithmetic operators are the symbols that are used to perform basic mathematical operations like
addition, subtraction, multiplication, division and percentage modulo. The following table provides
information about arithmetic operators.
The addition operator can be used with numerical data types and character data type. When it is
used with numerical values, it performs mathematical addition and when it is used with character data
type values, it performs concatenation (appending).
The remainder of the division operator is used with integer data type only.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5%2=1
57
58
59
60
61
62
63
Relational Operators (<, >, <=, >=, ==, !=)
64
The relational operators are the symbols that are used to compare two values. That means the relational
operators are used to check the relationship between two values. Every relational operator has two results TRUE
or FALSE. In simple words, the relational operators are used to define conditions in a program. The following
table provides information about relational operators.
Operator Meaning Example
Returns TRUE if the first value is smaller than second value
< 10 < 5 is FALSE
otherwise returns FALSE
Returns TRUE if the first value is larger than second value
> 10 > 5 is TRUE
otherwise returns FALSE
Returns TRUE if the first value is smaller than or equal to second
<= 10 <= 5 is FALSE
value otherwise returns FALSE
Returns TRUE if the first value is larger than or equal to second
>= 10 >= 5 is TRUE
value otherwise returns FALSE
== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE
65
66
67
68
Logical Operators (&&, ||, !)
69
The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.
Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE then complete
condition becomes FALSE.
Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE then complete
condition becomes TRUE.
Operator Meaning Example
The increment and decrement operators are called unary operators because both need only one
operand. The increment operators adds one to the existing value of the operand and the decrement
operator subtracts one from the existing value of the operand. The following table provides
information about increment and decrement operators.
The increment and decrement operators are used Infront of the operand (++a) or after the operand
(a++). If it is used in front of the operand, we call it as pre-increment or pre-decrement and if it is
used after the operand, we call it as post-increment or post-decrement.
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable
(Lvalue). The assignment operator is used in different variants along with arithmetic operators. The
following table describes all the assignment operators in the C programming language.
Operator Meaning Example
= Assign the right-hand side value to left-hand side variable A = 15
A += 10
+= Add both left and right-hand side values and store the result into left-hand side variable
⇒ A = A+10
Subtract right-hand side value from left-hand side variable value and store the result into left- A -= B
-=
hand side variable ⇒ A = A-B
Multiply right-hand side value with left-hand side variable value and store the result into left- A *= B
*=
hand side variable ⇒ A = A*B
Divide left-hand side variable value with right-hand side variable value and store the result into A /= B
/=
the left-hand side variable ⇒ A = A/B
Divide left-hand side variable value with right-hand side variable value and store the A %= B
%=
remainder into the left-hand side variable ⇒ A = A%B
76
77
Bitwise Operators (&, |, ^, ~, >>, <<)
78
The bitwise operators are used to perform bit-level operations in the c programming language. When we use the bitwise operators,
the operations are performed based on the binary values. The following table describes all the bitwise operators in the C
programming language. Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example
A&B
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0
⇒ 16 (10000)
A|B
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1
⇒ 29 (11101)
A^B
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1
⇒ 13 (01101)
~A
~ the result of Bitwise once complement is negation of the bit (Flipping)
⇒ -26
the Bitwise left shift operator shifts all the bits to the left by the specified number A << 2
<<
of positions ⇒ 100 (1100100)
the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
>>
number of positions ⇒ 6 (00110)
79
80
Conditional Operator (?:)
81
The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first we verify a condition, then we perform one
operation out of the two operations based on the condition result. If the condition is TRUE the first
option is performed, if the condition is FALSE the second option is performed. The conditional
operator is used with the following syntax.
Condition ? TRUE Part : FALSE Part;
Example
A = (10<15)?100:200; ⇒ A value is 100
82
83
84
Special Operators (sizeof,is, as,typeof, etc.)
85
int sizeof(type);
It accepts the type and returns an int value – which is the size of that type in
bytes.
86
is operator
87
The is operator is used to check if the run-time type of an object is compatible with
the given type or not.
The expression with the type-testing is operator has the following form.
E is T
where E is an expression that returns a value and T is the name of a type or a type
parameter.
The is operator returns true when an expression result is non-null and any of the
following conditions are true:
The run-time type of an expression result is T.
The run-time type of an expression result derives from type T, implements interface T, or another
implicit reference conversion exists from it to T.
A boxing or unboxing conversion exists from the run-time type of an expression result to type T.
88
89
As operator
90
E is T
91
92
Difference between is and as operator
93
typeof() is an operator in C#, it is used to get the type (system type) of with class
name of a given type.
By using typeof() operator, we can get the name of the type, namespace name. It
works with only compile-time known types.
typeof() operator does not work with the variables or instances. If you want to get
the type of a variable, you can use GetType() method.
There are main 3 properties to get the details about the type:
typeof(type).Name or this.GetType().Name – It returns the class name only.
typeof(type).FullName or this.GetType().FullName – It returns the class name along with
the namespace.
typeof(type).Namespace or this.GetType().Namespace – It returns the namespace only.
95
96
Checked and unchecked operator
97
22-06-2021 II MCA
Expressions
2
The simplest C# expressions are literals (for example, integer and real
numbers) and names of variables. We can combine them into complex
expressions by using operators.
An expression in C# is a combination of operands (variables, literals,
method calls) and operators that can be evaluated to a single value. To
be precise, an expression must have at least one operand but may not
have any operator.
Typically, an expression produces a result and can be included in
another expression.
3
Operator precedence and associativity determine the order in which the operations
in an expression are performed.
In an expression with multiple operators, the operators with higher precedence are
evaluated before the operators with lower precedence.
When operators have the same precedence, associativity of the operators
determines the order in which the operations are performed:
Left-associative operators are evaluated in order from left to right. Except for the assignment
operators, all binary operators are left-associative.
Right-associative operators are evaluated in order from right to left. The assignment operators
and the conditional operator ?: are right-associative.
We can use parentheses to change the order of evaluation imposed by operator
precedence and associativity.
The following table lists the C# operators starting with the highest precedence to the
lowest. The operators within each row have the same precedence.
19
20
21
22
23
Control Statements
24
The control statements are used to control the flow of execution of the
program.
If we want to execute a specific block of instructions only when a certain
condition is true, then control statements are useful.
If we want to execute a block repeatedly, then loops are useful.
C# classifies these control statements into two categories
Conditional execution
Unconditional execution
Conditional Unconditional
Do-
while for foreach
while
Simple if statement is used to verify the given condition and executes the
block of statements based on the condition result.
The simple if statement evaluates specified condition.
If it is TRUE, it executes the next statement or block of statements.
If the condition is FALSE, it skips the execution of the next statement or block
of statements.
Simple if statement is used when we have only one option that is executed or
skipped based on a condition.
The general syntax and execution flow of the simple if statement is as follows.
27
28
29
30
31
If-else statement
32
The if-else statement is used to verify the given condition and executes only
one out of the two blocks of statements based on the condition result.
The if-else statement evaluates the specified condition.
If it is TRUE, it executes a block of statements (True block).
If the condition is FALSE, it executes another block of statements (False
block).
The if-else statement is used when we have two options and only one
option has to be executed based on a condition result (TRUE or FALSE).
The general syntax and execution flow of the if-else statement is as
follows.
33
34
35
Nested if statement
36
C# provides the while loop to repeatedly execute a block of code as long as the
specified condition returns false.
The while loop starts with the while keyword, and it must include a Boolean
conditional expression inside brackets that returns either true or false.
It executes the code block until the specified conditional expression returns false.
In a while loop, initialization should be done before the loop starts, and increment or
decrement steps should be inside the loop.
The statement(s) inside the while loop may be a single statement or a block of
statements.
The key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body is skipped and the first
statement after the while loop is executed.
58
59
60
61
62
63
do while Statement
64
The do while loop is the same as while loop except that it executes the code block at
least once.
The do-while loop starts with the do keyword followed by a code block and a
boolean expression with the while keyword.
The do while loop stops execution exits when a boolean condition evaluates to false.
Because the while(condition) specified at the end of the block, it certainly executes
the code block at least once.
In a while loop, initialization should be done before the loop starts, and increment or
decrement steps should be inside the loop.
The statement(s) inside the while loop may be a single statement or a block of
statements.
The key point of the do while loop is that the loop will executed atleast once, even
on the first time When the condition is tested and the result is false.
This is the reason, do while is called as exit controlled loop.
65
66
67
68
for loop
69
The iterator section can contain zero or more of the following statement
expressions, separated by commas:
prefix or postfix increment expression, such as ++i or i++
assignment
invocation of a method
The in keyword used along with foreach loop is used to iterate over the
iterable-item.
The in keyword selects an item from the iterable-item on each iteration and
store it in the variable element.
On first iteration, the first item of iterable-item is stored in element. On second
iteration, the second element is selected and so on.
The number of times the foreach loop will execute is equal to the number of
elements in the array or collection.
77
78
79
80
81
82
83
break Statements
84
A Continue statement jumps out of the current loop condition and jumps
back to the starting of the loop code.
It is represented by continue;
Continue statement can be used in the following scenarios:
for loop (For loop & nested for loop.
foreach loop (foreach loop & nested foreach loop.
While (while loop & nested while loop).
Do while (do while loop and nested while loop)
Switch case (Switch cases and nested switch cases)
91
92
93
goto statement
94
28-06-2021 II MCA
Arrays
2
Jagged array is a array of arrays such that member arrays can be of different
sizes.
In other words, the length of each array index can differ.
The elements of Jagged Array are reference types and initialized to null by default.
Jagged Array can also be mixed with multidimensional arrays. Here, the number of
rows will be fixed at the declaration time, but you can vary the number of columns.
In Jagged arrays, user has to provide the number of rows only. If the user is also
going to provide the number of columns, then this array will be no more Jagged
Array.
The elements of Jagged Array must be initialized before its use.
37
38
39
40
Array Class
41
Array Class provides methods for creating, manipulating, searching, and sorting
arrays, thereby serving as the base class for all arrays in the common language
runtime.
Array class is defined in the System namespace, is the base class for arrays in C#.
Array class is an abstract base class that means we cannot create an instance of the
Array class.
Properties Definition
IsFixedSize Return a value indicating if an array has a fixed size or not.
IsReadOnly Returns a value indicating if an array is read-only or not.
LongLength Returns a 64-bit integer that represents a total number of items in all the dimensions of an array.
Length Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.
Rank Returns the number of dimensions of an array.
42
BinarySearch() Searches a one-dimensional sorted Array for a value, using a binary search algorithm.
Copy() Copy array elements to another elements
Resize() Changes the number of elements of a one-dimensional array to the specified new size.
Clear() Sets a range of elements in the Array to zero, to false, or to null, depending on the element
type.
IndexOf () Searches for the specified object and returns the index of its first occurrence in a one-
dimensional array or in a range of elements in the array.
LastIndexOf () Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion
of the Array.
Sort() Sorts the elements in a one-dimensional array.
Reverse() Reverses the order of the elements in a one-dimensional Array or in a portion of the Array
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
ArrayList
59
PROPERTIES Definition
Capacity Gets or sets the number of elements that the ArrayList can
contain.
Count Gets the number of elements actually contained in
the ArrayList.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed
size.
IsReadOnly Gets a value indicating whether the ArrayList is read-
only.
Item[Int32] Gets or sets the element at the specified index.
Methods Description
Add() Add() method adds single elements at the end of ArrayList.
AddRange() AddRange() method adds all the elements from the specified collection into ArrayList.
Insert() Insert() method insert a single elements at the specified index in ArrayList.
InsertRange() InsertRange() method insert all the elements of the specified collection starting from specified index in ArrayList.
Remove() Remove() method removes the specified element from the ArrayList.
RemoveRange() RemoveRange() method removes a range of elements from the ArrayList.
RemoveAt() Removes the element at the specified index from the ArrayList.
Sort() Sorts entire elements of the ArrayList.
Reverse() Reverses the order of the elements in the entire ArrayList.
Contains Checks whether specified element exists in the ArrayList or not. Returns true if exists otherwise false.
Clear Removes all the elements in ArrayList.
CopyTo Copies all the elements or range of elements to compitible Array.
GetRange Returns specified number of elements from specified index from ArrayList.
IndexOf Search specified element and returns zero based index if found. Returns -1 if element not found.
61
ToArray Returns compitible array from an ArrayList.
62
STRINGS IN C#
02-07-2021 II MCA
Character Handling
2
Since a string is basically just a range of characters, .NET actually uses a list of char's to represent a string. That
also means that you can pull out a single char from a string, or iterate over a string and get each character as a
char data type:
string helloWorld = "Hello, world!";
foreach(char c in helloWorld)
{
Console.WriteLine(c);
}
Generally char is also considered as a numerical value, where each character has a specific number in the
Unicode "alphabet".
In C#, it is very easy to go from a char data type to its numeric representation.
string helloWorld = "Hello, world!";
foreach(char c in helloWorld)
{
Console.WriteLine(c + ": " + (int)c);
}
Properties Description
MaxValue Represents the largest possible value of a Char. This field is constant.
MinValue Represents the smallest possible value of a Char. This field is constant
Methods Description
Compares this instance to a specified Char object and indicates whether this instance
CompareTo(Char) precedes, follows, or appears in the same position in the sort order as the specified Char
object.
Equals(Char) Returns a value that indicates whether this instance is equal to the specified Char object.
IsControl(Char) Indicates whether the specified Unicode character is categorized as a control character.
IsDigit(Char) Indicates whether the specified Unicode character is categorized as a decimal digit.
4
IsLetter(Char) Indicates whether the specified Unicode character is categorized as a Unicode letter.
Methods Description
IsLetterOrDigit(Char) Indicates whether the specified Unicode character is categorized as a letter or a decimal digit.
IsLower(Char) Indicates whether the specified Unicode character is categorized as a lowercase letter.
IsNumber(Char) Indicates whether the specified Unicode character is categorized as a number.
IsPunctuation(Char) Indicates whether the specified Unicode character is categorized as a punctuation mark.
IsSeparator(Char) Indicates whether the specified Unicode character is categorized as a separator character.
IsSymbol(Char) Indicates whether the specified Unicode character is categorized as a symbol character.
IsUpper(Char) Indicates whether the specified Unicode character is categorized as an uppercase letter.
IsWhiteSpace(Char) Indicates whether the specified Unicode character is categorized as white space.
Parse(String) Converts the value of the specified string to its equivalent Unicode character.
ToLower(Char) Converts the value of a Unicode character to its lowercase equivalent.
ToString() Converts the value of this instance to its equivalent string representation.
Converts the value of this instance to its equivalent string representation using the specified culture-
ToString(IFormatProvider)
specific format information.
ToUpper(Char) Converts the value of a Unicode character to its uppercase equivalent.
5 Converts the value of the specified string to its equivalent Unicode character. A return code
TryParse(String, Char)
indicates whether the conversion succeeded or failed.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Strings
21
Strings are collections of characters that are grouped together to form words or
sentences.
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’).
The Length property of a string represents the number of Char objects it contains, not
the number of Unicode characters.
In C#, the string keyword is an alias for String. Therefore, String and string are
equivalent, regardless it is recommended to use the provided alias string as it works
even without using System;.
The String class provides many methods for safely creating, manipulating, and
comparing strings.
Following are the ways to declare and initialize the strings.
22
23
24
In C#, the string is immutable, which means the string object cannot be
modified once it is created.
If any changes are made to the string object, like adding or modifying an
existing value, it will simply discard the old instance in memory and create a
new instance to hold the new value.
For example, when we create a new string variable “msg” with the text
“welcome”, a new instance will create a heap memory to hold this value.
Now, if we make any changes to the msg variable, like changing the text from
“welcome” to “welcome to C#”, then the old instance on heap memory will be
discarded, and another instance will create on heap memory to hold the
variable value instead of modifying the old instance in the memory.
25
StartsWith(String) It is used to check whether the beginning of this string instance matches the specified string.
27 It is used to retrieve a substring from this instance. The substring starts at a specified character position
Substring(Int32)
and continues to the end of the string.
Method Name Description
ToCharArray() It is used to copy the characters in this instance to a Unicode character array.
Trim() It is used to remove all leading and trailing white-space characters from the current String object.
It Is used to remove all trailing occurrences of a set of characters specified in an array from the current
TrimEnd(Char[])
String object.
It is used to remove all leading occurrences of a set of characters specified in an array from the current
TrimStart(Char[])
String object.
28
29
30
31
32
33
34
35
36
37
38
39
String.Format()
40
The following example illustrates how a StringBuilder object allocates new memory
and increases its capacity dynamically as the string assigned to the object expands.
The code creates a StringBuilder object by calling its default (parameterless)
constructor.
The default capacity of this object is 16 characters, and its maximum capacity is
more than 2 billion characters.
Appending the string "This is a sentence." results in a new memory allocation
because the string length (19 characters) exceeds the default capacity of the
StringBuilder object. The capacity of the object doubles to 32 characters, the new
string is added, and the length of the object now equals 19 characters. The code
then appends the string "This is an additional sentence." to the value of the
StringBuilder object 11 times. Whenever the append operation causes the length of
the StringBuilder object to exceed its capacity, its existing capacity is doubled and
the Append operation succeeds.
49
Memory allocation
50
If the length of the string assigned to the StringBuilder object in the constructor
call exceeds either the default capacity or the specified capacity, the
Capacity property is set to the length of the string specified with the value
parameter.
we can explicitly define the maximum capacity of a StringBuilder object by
calling the StringBuilder(Int32, Int32) constructor. we can't change the
maximum capacity by assigning a new value to the MaxCapacity property,
because it is read-only.
StringBuilder Constructors
52
Constructor Description
We can create an object of the StringBuilder class using the new keyword and
passing an initial string. The following example demonstrates creating StringBuilder
objects.
Optionally, you can also specify the maximum capacity of the StringBuilder object
using overloaded constructors.
StringBuilder sb = new StringBuilder(); //string will be appended later
StringBuilder sb = new StringBuilder("Hello World!");
StringBuilder sb = new StringBuilder(50); //string will be appended later
StringBuilder sb = new StringBuilder("Hello World!", 50);
Above, C# allocates a maximum of 50 spaces sequentially on the memory heap.
This capacity will automatically be doubled once it reaches the specified capacity.
We can also use the capacity or length property to set or retrieve the StringBuilder
object's capacity.
54
Using for loop, it is possible to iterate and get or set a character at the
specified index.
Example: StringBuilder Iteration
StringBuilder sb = new StringBuilder("Hello World!");
for(int i = 0; i < sb.Length; i++)
Console.Write(sb[i]); // output: Hello World!
Retrieve String from StringBuilder
The StringBuilder is not the string. Use the ToString() method to retrieve a
string from the StringBuilder object.
Example: Retrieve String from StringBuilder
StringBuilder sb = new StringBuilder("Hello World!");
String greet = sb.ToString(); //returns "Hello World!"
StringBuilder Properties
55
Property Description
Gets or sets the maximum number of characters that can be contained in the memory
StringBuilder.Capacity
allocated by the current instance.
StringBuilder.Chars[Int32] Gets or sets the character at the specified character position in this instance.
08-07-2021 II MCA
Object Oriented Programming (OOPS)
2
The mechanism by which the data and functions are bound together into a
single unit is known as Encapsulation.
It implements abstraction.
Encapsulation is about binding the data variables and functions together in
class. It can also be called Data Binding.
Encapsulation is the most striking feature of a class.
The data is not accessible to the outside world, and only those functions
which are wrapped in the class can access it. These functions provide the
interface between the object's data and the program.
This encapsulation of data from direct access by the program is called
Data Hiding or Information Hiding.
Class
9
A class definition starts with the keyword class followed by the class name; and the class
body enclosed by a pair of curly braces.
Class is a keyword and class name is any valid C# identifier. Everything inside the class is
optional.
Class members may have fields, methods, constructors, destructors, properties, indexers,
delegates.
Eg:
class Program
{
int a=10;
void display();
public static void Main()
{
}
}
Access Modifiers
14
The Access Specifiers in C# are also called access modifiers which are used to
define the scope of the type as well as the scope of their members. That is who can
access them and who cannot access them are defined by the Access Specifiers.
C# supports 5 access specifiers, they are as follows
Private
Internal
Protected
Protected Internal
Public
Members that are defined in a type with any scope or specifiers are always
accessible within that type; restriction comes into the picture only when they try to
access them outside of the type.
The default access specifier for a class type is internal. Default access for the
members is private.
15
CLASS EXAMPLES
Examples
17
18
19
20
21
22
23
24
25
EXAMPLES OF ACCESS
SPECIFIERS
26
27
28
29
30
31
32
33
Constructors
34
There are five types of constructors available in C#, they are as follows
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor
In C#, within a class, we can define any number of constructors. But the
most important point that you need to remember is that each and every
constructor must have a different signature.
Different signature means the number, type, and parameter order
should be different.
So in a class, we can define one no-argument constructor plus ‘n’ number
of parameterized constructors in C#.
46
47
48
Copy Constructor
49
A destructor method gets called when the object of the class is destroyed.
The object of a class in C# will be destroyed by the garbage collector in any of
the following cases
Case1: At the end of a program execution each and every object that is associated
with the program will be destroyed by the garbage collector.
Case2: The Implicit calling of the garbage collector occurs sometime in the middle of
the program execution provided the memory is full so that the garbage collector will
identify unused objects of the program and destroys them.
Case 3: The Explicit calling of the garbage collector can be done in the middle of
program execution with the help of the “GC.Collect()” statement so that if there are
any unused objects associated with the program will be destroyed in the middle of
the program execution.
63
64
65
66
67
68
INHERITANCE
13-07-2021 II MCA
Inheritance
2
The process of creating a new class from an existing class such that the new
class acquires all the properties and behaviors of the existing class is called
inheritance.
The properties (or behaviors) are transferred from which class is called the
superclass or parent class or base class whereas the class which derives the
properties or behaviors from the superclass is known as a subclass or child
class or derived class.
Inheritance is the concept which is used for code reusability and changeability
purpose. Here changeability means overriding the existed functionality or
feature of the object or adding more functionality to the object.
3
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance
Multiple Inheritance
Single Inheritance: When a class is derived from a single base class then the
inheritance is called single inheritance.
Hierarchical Inheritance: Hierarchical inheritance is the inheritance where
more than one derived class is created from a single base class.
6
Default Superclass: Except Object class, which has no superclass, every class has
one and only one direct superclass(single inheritance). In the absence of any other
explicit superclass, every class is implicitly a subclass of Object class.
Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because C# does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported by
C#.
Inheriting Constructors: A subclass inherits all the members (fields, methods) from its
superclass. Constructors are not members, so they are not inherited by subclasses, but
the constructor of the superclass can be invoked from the subclass.
Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has properties(get and set methods) for
accessing its private fields, then a subclass can inherit.
8
In inheritance, the constructor of the parent class must be accessible to its child
class otherwise the inheritance will not possible because when we create the
child class object first it goes and calls the parent class constructor so that the
parent class variable will be initialized and we can consume them under the
child class.
In inheritance, the child classes can consume the parent class members but the
parent class does not consume child class members that are purely defined in
the child class.
Class members Visibility
9
10
Single Inheritance
11
In the Multilevel inheritance, a derived class will inherit a base class and as
well as the derived class also act as the base class to other class.
For example, three classes called A, B, and C, as shown in the below image,
where class C is derived from class B and class B, is derived from class A.
In this situation, each derived class inherit all the characteristics of its base
classes. So class C inherits all the features of class A and B.
In multilevel inheritance the level of inheritance can be extended to any
number of level depending upon the relation.
Multilevel inheritance is similar to relation between grandfather, father and
child.
23
24
25
Hierarchical inheritance
26
When a class is declared with in another class, the inner class is called as Nested class
(i.e. the inner class) and the outer class is known as Enclosing class.
Nested class can be defined in private as well as in the public section of the Enclosing
class.
The inner class can act as a helper class to serve the outer class.
A method in the inner class can access all members including private members of its
outer class.
A public inner class is accessed within the scope of the outer class.
The members in an inner class hide the members having the same name in its outer class.
Thus name hiding is possible by nesting blocks or nesting classes.
35
Constants are immutable values which are known at compile time and do not change
for the life of the program.
Constants are declared with the const modifier.
Only the C# built-in types can be declared as const.
User-defined types, including classes, structs, and arrays, cannot be declared as
const.
C# does not support const methods, properties, or events.
It’s mandatory to initialize constant fields with required values during the declaration
itself; otherwise, we will get compile-time errors in our C # application.
Following is the syntax of defining constant fields using const keyword in c#
programming language.
const data_type field_name = "value";
41
The following are the different ways of declaring and initializing constant
variables in the c# programming language.
// Constant variables
const string name = "Praveen Sundar";
const string location = "Vellore";
const int age = 18;
public const int Months = 12, Weeks = 52, Days = 365;
public const int Months = 12;
public const int Weeks = 52;
public const int Days = 365;
public const double DaysPerWeek = (double) Days / (double) Weeks;
public const double DaysPerMonth = (double) Days / (double) Months;
Read Only Members
42
The variable which is declared by using the readonly keyword is known as a read-only
variable.
The read-only variable’s value cannot be modified once after its initialization.
It is not mandatory or required to initialize the read-only variable at the time of its
declaration like a constant. You can initialize the read-only variables under a constructor
but the most important point is that once after initialization, you cannot modify the value.
The behavior of a read-only variable is similar to the behavior of a non-static variable.
That is, it maintains a separate copy for each object. The only difference between these
two is non-static variables can be modified while the read-only variables cannot be
modified.
A constant variable is a fixed value for the complete class whereas a read-only variable is
a fixed value but specific to one object of the class.
43
44
Properties
45
In order to encapsulate and protect the data members (i.e. fields), we use properties in
C#.
The Properties in C# are used as a mechanism to set and get the values of a class
outside of that class.
If a class contains any value in it and if we want to access those values outside of that
class, then you can provide access to those values in two different ways
By storing the value under a public variable we can give access to the value outside of the
class.
By storing that value in a private variable we can also give access to that value outside of
the class by defining a property for that variable.
A property in C# is a member of a class which is used to set and get the data from a
data field of a class.
46
Whenever we create a property, the data type of the property must be the
same as the data type of the data field for which we create the property.
A property can never accept any arguments.
The most important point that you need to remember is. a property in C# is
never used to store data, it just acts as an interface to transfer the data.
We use the Properties as they are the public data members of a class, but they
are actually special methods called accessors.
The Assessors are nothing but special methods which are used to set and get the
values from the underlying data member. Assessors are of two types such as
set accessor
get accessor
The set accessor is used to set the data (i.e. value) into a data field. This set accessor
contains a fixed variable named “value”.
47
Whenever we call the property to set the data, whatever data (value) we are
supplying that will come and store in the variable “value” by default.
Syntax:
set { Data Field Name = value; }
The get accessor is used to get the data from the data field. Using this get accessor
you cannot set the data.
Syntax:
get { return Data Field Name; }
The default accessibility modifier of the accessor is same as the accessibility
modifier of property.
If the accessibility modifier of the accessors (both get and set) are the same within a
property then the accessors are known as Symmetric accessors.
48
On the other hand, if the accessibility modifier of the accessors is not the same within
a property then the accessors are known as Asymmetric accessors.
For example:
public int empid
{
protected set { _empid = value; }
get { return _empid; }
}
The C#.NET supports four types of properties. They are as follows
Read-only property
Write only property
Read Write property
Auto-implemented property
49
The Read-only property is used to read the data from the data field.
Using this property you cannot set the data into the data field. This property
will contain only one accessor i.e. “get” accessor.
Syntax:
AccessModifier Datatype PropertyName { get { return DataFieldName; } }
The Write-only property is used to write the data into the data field of a
class.
Using this property you cannot read the data from the data field. This
property will contain only one accessor i.e. set accessor.
Syntax:
AccessModifier Datatype PropertyName { set { DataFieldName = value; } }
50
The Read-Write property is used for both read the data from the data field as well as write the
data into the data field. This property will contain two accessor i.e. set and get.
Syntax:
AccessModifier DataType PropertyName
{
set
{
DataFieldName = value;
}
get
{
Return DataFieldName;
}
}
51
52
Auto-Implemented Properties in C#
53
If we do not have any additional logic while setting and getting the data from a
data field then we can make use of the auto-implemented properties which was
introduced in C# 3.0
The Auto-implemented property reduces the amount of code that we have to write.
When we use auto-implemented properties, the C# compiler implicitly creates a
private, anonymous field behind the scene which is going to hold the data.
Syntax:
Access specifier Datatype Property name
{
get;
set;
}
Example: public int A { Get; Set; }
54
55
Need of properties in real-time applications
56
A good design of a class is achieved by hiding implementation details of the methods and
preventing direct access to data fields. Abstract classes and interfaces help in hiding
implementations. Preventing direct access to the fields is achieved by making the fields private.
Only by making the fields private the benefits of data integrity do not come automatically.
The programmer must provide validity checking. Methods that set the values of private data
should verify whether the input values are valid or not. If the values are not proper, the set
method may provide an appropriate value.
Properties appear to the outside world as fields, but allow processing when their values are
read or modified. They are usually used to modify the behavior at runtime.
Even though a public set accessor seems to allow other methods to read the data at will, it is
possible to control a new value appropriate for the typical application. The access is restricted
by proper implementation of the accessors by the programmers. Thus the benefits of data
integrity is obtained by providing validity checking in the accessor methods of properties.
57
58
59
60
61
Properties can also validate the data before storing into the data fields.
Indexers
62
An indexer can be defined the same way as property with this keyword and
square brackets [].
Actually an indexer is a special kind of property and includes get and set
accessors to specify its behaviour. Hence, indexers and properties share the
same syntax.
An indexer is defined in the same way as a property is defined with following
differences:
The Indexer takes an index argument as its subscript.
The class itself is being treated as an array and the keyword this is used
as the name of the indexer in the indexer definition.
Syntax
64
Indexers Properties
Indexers are created with this keyword. Properties don't require this keyword.
Indexers are accessed using indexes. Properties are accessed by their names.
Indexer are instance member, so can't be static. Properties can be static as well as instance members.
Generic means the general form, not specific. In C#, generic means not specific to a
particular data type. In otherwards, Generics allow you to write a class or method
that can work with any data type. we always write the specifications for the class or
the method, with substitute parameters for data types.
When the compiler encounters a constructor for the class or a function call for the
method, it generates code to handle the specific data type.
A generic type is declared by specifying a type parameter in an angle brackets
after a type name, e.g. TypeName<T> where T is a type parameter.
A type parameter is a placeholder for a particular type specified when creating an
instance of the generic type.
Generic Class
70
Generic classes are defined using a type parameter in an angle brackets after the class name.
The following defines a generic class.
Example: Define Generic Class
class DataStore<T>
{
public T Data { get; set; }
}
Above, the DataStore is a generic class. T is called type parameter, which can be used as a type
of fields, properties, method parameters, return types, and delegates in the DataStore class.
For example, Data is generic property because we have used a type parameter T as its type
instead of the specific data type.
It is not required to use T as a type parameter. You can give any name to a type parameter.
Generally, T is used when there is only one type parameter.
Instantiating Generic Class
71
You can assign a string value to the Data property. Trying to assign values other than string will
result in a compile-time error.
DataStore<string> store = new DataStore<string>();
store.Data = "Hello World!";
//store.Data = 123; //compile-time error
A generic class increases the reusability. The more type parameters mean more reusable it
becomes. However, too much generalization makes code difficult to understand and maintain.
A generic class can be a base class to other generic or non-generic classes or abstract classes.
A generic class can be derived from other generic or non-generic interfaces, classes, or abstract
classes.
we can create your own generic interfaces, classes, methods, events, and delegates.
we may create generic classes constrained to enable access to methods on particular data
types.
we may get information on the types used in a generic data type at run-time by means of
reflection.
Generic Methods
79
A method declared with the type parameters for its return type or parameters is
called a generic method.
80
Above, the AddorUpdate() and the GetData() methods are generic methods. The actual
data type of the item parameter will be specified at the time of instantiating the
DataStore<T> class, as shown below.
The generic parameter type can be used with multiple parameters with or without non-
generic parameters and return type. The followings are valid generic method overloading.
81
82
04-08-2021 II MCA
2
It is a process of creating multiple methods in a class with the same name but with
a different signature.
In C#, It is also possible to overload the methods in the derived classes, which
means, it allows us to create a method in the derived class with the same name as
the method name defined in the base class.
In simple words, we can say that the Function Overloading in C# allows a class to
have multiple methods with the same name but with a different signature.
So in C# functions or methods can be overloaded based on the number, type (int,
float, etc.), order, and kind (Value, Ref or Out) of parameters.
The signature of a method consists of the name of the method and the data type,
number, order, and kind (Value, Ref or Out) of parameters.
6
If two methods have the same method name those methods are considered
overloaded methods.
Then the rule we should check is both methods must have different
parameter types/number/order. But there is no rule on return type, non-
accessibility modifier and accessibility modifier means overloading
methods can have their own return type, non-accessibility modifier, and
accessibility modifier because overloading methods are different methods.
Methods can be overloaded in the same or in super and sub classes
because overloaded methods are different methods.
A method that is defined in a class can also be overloaded under its child
class. It is called inheritance-based overloading.
7
8
9
Operator Overloading
10
Similar to any other function, an overloaded operator has a return type and a
parameter list.
Operator is the keyword which is used to implement operator overloading. The
return type of operator overload can never be void.
In operator overloading preference is always given to user-defined implementations
rather than predefined implementations.
In user-defined implementations, syntax and precedence cannot be modified.
We can overload all the binary operators i.e +, -, *, /, %, &, |, <<, >>.
We can overload all the unary operators i.e. ++, –, true, false, + , -, ~.
Some operators like &&, ||,[] ,() cannot be overloaded.
We can overload relational operators in pairs. These are ==, =, <, >, <= , >= etc.
When binary operators are overloaded, the left hand object must be an object of the relevant
class
12
13
14
15
16
17
18
In C#, The process of re-implementing the base class non-static method in the
subclass with the same prototype (same signature defined in the superclass) is called
Function Overriding or Method Overriding.
In C#, the Method Overriding is also called run time polymorphism or late binding.
The Method Overriding in C# can be achieved using Override & Virtual keywords
and the inheritance principle.
The implementation of the subclass overrides (i.e. replaces) the implementation of
base class methods.
The overriding method is always going to be executed from the current class object.
If a method in sub-class contains the same signature as the base class non-private
non-static method, then the subclass method is treated as the overriding method and
the superclass method is treated as the overridden method.
20
To override a parent class method in its child class, first the method in the parent
class must be declared as virtual by using the keyword virtual, then only the child
classes get the permission for overriding that method.
Declaring the method as virtual is marking the method as overridable. If the child
class wants to override the parent class virtual method then the child class can do it
with the help of the override modifier. But overriding the method under child class is
not mandatory for the child classes.
Syntax:
Class1:
Public virtual void show(){} //virtual function (overridable)
Class2: Class1
Public override void show(){} //overriding
21
Once we re-implement the parent class methods under the child class, then the
object of the child class calls its own methods but not its parent class method.
if you want to still consume or call the parent class’s methods from the child
class, then it can be done in two different ways.
By creating the parent class object under the child class, we can call the
parent class methods from the child class, or by using the base keyword, we
can call parent class methods from the child class.
22
23
24
25
26
27
Method Overloading Method Overriding
It is an approach of defining multiple methods with the It is an approach of defining multiple methods with the
same name but with a different signature. same name and with the same signature.
Overloading a method can be performed within a class or Overriding of methods is not possible within the same
within the child classes also. class it must be performed under the child classes.
To overload a parent class method under the child class, To override a parent class method under the child class,
the child class does not require permission from the first, the child class requires explicit permission from its
parent. parent.
This is all about defining multiple behaviors to a method. This is all about changing the behavior of a method.
Use the virtual keyword for the base class function and
No separate keywords are used to implement function
override keyword in the derived class function to
overloading.
28 implement function overriding.
Method Hiding
29
C# also provides a concept to hide the methods of the base class from derived class, this
concept is known as Method Hiding. It is also known as Method Shadowing. In method hiding, you
can hide the implementation of the methods of a base class from the derived class using the new
keyword.
Usually, we will get a compiler warning if we miss the new keyword. This is also used for re-
implementing a parent class method under child class.
Reimplementing parent class methods under child classes can be done using two different
approaches, such as
Method overriding
Method hiding
In the first case, we re-implement the parent class methods under child classes with the
permission of parent class because here in parent class the method is declared as virtual giving
permission to the child classes for overriding the methods.
In the 2nd approach, we re-implement the method of parent class even if those methods are not
declared as virtual that is without parent permission we are reimplementing the methods.
30
31
32
33
Abstract Class
34
Abstract methods are usually declared where two or more subclasses are
expected to fulfill a similar role in a different manner.
The subclasses are required to fulfill an interface, so the abstract superclass
might provide several of the interface methods, but leave the subclasses to
implement their own variations of the abstract methods.
A method that does not have a body is called an abstract method. It is
declared with the modifier abstract. It contains only a Declaration/signature
and does not contain the implementation/body/definition of the method.
An abstract function should be terminated with a semicolon. Overriding an
abstract function is compulsory.
Rules of Abstract Method and Abstract Class
37
Rule1: If a method does not have the body, then it should be declared as
abstract using the abstract modifier else it leads to a compile-time error:
“must declare a body because it is not marked abstract, extern, or partial”.
Rule2: If a class has an abstract method it should be declared as abstract by
using the keyword abstract else it leads to a compile-time error:
Rule3: If a class is declared as abstract it cannot be instantiated violation
leads to compile-time Error.
Rule4: The sub-classes of an abstract class should override all the abstract
methods or it should be declared as abstract else it leads to the compile-time
error:
38
39
40
41
42
43
44
Differences between overriding methods and abstract methods
45
The concept of the abstract method is near similar to the concept of method
overriding because in method overriding if a Parent class contains any virtual
methods in it, then those methods can be re-implemented under the child class
by using the override modifier.
In a similar way, if a parent class contains any abstract methods in it, those
abstract methods must be implemented under the child class by using the same
override modifier.
The main difference between method overriding and abstract method is in the
case of method overriding the child class re-implementing the method is
optional but in the case of the abstract method, the child class implementing
the method is mandatory.
Sealed Class & Methods
46
In C#, sealed is a keyword used to stop inheriting the particular class from other
classes.
Based on our requirements, it is possible to prevent overriding the particular
properties or methods.
Generally, while creating a particular class it is possible to inherit all the
properties and methods in any class.
If we want to restrict access to a defined class and its members, then by using a
sealed keyword, we can prevent other classes from inheriting the defined class.
In C#, a sealed class can define by using a sealed keyword.
In C#, if we define a class with the sealed keyword, then we don’t have a
chance to inherit that particular class.
Points to be considered
47
A class that contains one or more abstract methods is known as A class from which it is not possible to derive a new class is
an abstract class. known as a sealed class.
The abstract class can contain abstract and non-abstract The sealed class can contain non-abstract methods; it cannot
methods. contain abstract and virtual methods.
We need to use the keyword abstract to make any class We need to use the keyword sealed to make any class as
abstract. sealed.
An abstract class cannot be the bottom-most class within the The sealed class should be the bottom-most class within the
inheritance hierarchy. inheritance hierarchy.
Partial Class and Methods
Partial Classes are the new feature that has been added in C# 2.0 which allows us to
define a class on multiple files i.e. we can physically split the content of the class into
different files but even physically they are divided but logically it is one single unit only.
A class in which code can be written in two or more files is known as a partial class.
To make any class partial we need to use the keyword partial.
Partial classes allow us to split a class definition into 2 or more files.
It is also possible to split the definition of a struct or an interface over two or more
source files.
Each source file will contain a section of the class definition, and all parts are combined
into a single class when the application is compiled.
Rules for Partial Classes
All the partial class definitions must be in the same assembly and namespace.
All the parts must have the same accessibility like public or private, etc.
If any part is declared abstract, then the whole type is considered abstract.
If any part is declared sealed, then the whole type is considered sealed.
If any part declares a base type, then the whole type inherits that class.
Any class member declared in a partial definition are available to all other parts.
Different parts can have different base types and so the final class will inherit all
the base types.
The Partial modifier can only appear immediately before the keywords class, struct,
or interface.
Partial Methods
A partial class may contain a partial method.
One part of the class contains the signature of the method.
An optional implementation may be defined in the same part or another part.
If the implementation is not supplied, then the method and all calls are
removed at compile time.
The implementation can be provided in the same physical file or in another
physical file that contains the partial class.
Interface
66
The class or struct that implements an interface must provide an implementation for
all the members specified in the interface definition.
Generally, C# will not support multiple inheritance of classes, but that can achieve
by using an interface.
Also, a structure in C# cannot be inherited from another structure or class, but that
can inherit by using interfaces.
If we define an abstract class in place of an interface, a service provider cannot
implement multiple specifications so that the service provider cannot have multiple
businesses.
In C#, we can define an interface by using interface keyword.
68
Here the keyword interface tells that Example is an interface containing one abstract
method i.e. show().
By default, the members of an interface are public and abstract.
An interface can contain
Abstract methods
Properties
Indexes
Events
An interface cannot contain
Non-abstract functions
Data fields
Constructors
Destructors
70
n Multiple inheritance, one class can have more than one superclass
and inherit features from all its parent classes.
C# doesn't allow multiple inheritance with classes but it can be
implemented using interface. The reason behind is:
Multiple inheritance add too much complexity with little benefit.
There are huge chances of conflicting base class member. For example,
if there is a method calculate() in two base class and both are doing
different calculation. What happened if user call calculate() in child
class? Which method will work?
Inheritance with Interface provides same job of multiple inheritance.
Multiple Inheritance inject a lots of burden into implementation and it
cause slow program execution.
77
78
The list of interfaces following the colon(:) in the class declaration is known as
baselist.
It is possible to include only one class in the baselist.
When the baselist of a class contains a base class and interfaces, the base
class must be written first in the base list.
Maximum of one class and any number of interfaces are allowed in the
baselist.
80
81
DELEGATES
12-08-2021 II MCA
83
The dictionary of delegate is "a person acting for another person". In C#, it really
means a method acting for another method.
A delegate is another reference type introduced in C#.
An instance of a delegate encapsulates a reference to a method.
A delegate refers to either an instance method or a static method.
Delegates always refer to methods. They are defined at run-time.
By using a delegate, a method may be passed as an argument to another method.
A method that is passed to another method as an argument is called a callback
method or callback function.
Callback functions are used to pass a function as an argument in other languages.
A delegate can be declared in a class or an interface
All delegates are implicitly derived from the System.Delegate class.
84
A delegate can be declared using the delegate keyword followed by a function signature,
as shown below.
Where
modifier represents public, protected, internal, private and new.
delegate is the keyword representing the declaration as a delegate.
return type indicates the return type of the delegate
Delegate name is any valid identifier and is the name of the delegate that will be used to instantiate
delegate objects.
Parameters identifies the signature of the delegate
87
The new modifier is only permitted on delegates declared within another type, in
which case it specifies that such a delegate hides an inherited member by the same
name.
The method to be passed must be declared as a normal method with the same
return type and parameter list. It can be either static or instance method.
Since it is a class type, it can be defined in any place where a class definition is
permitted. That is, a delegate may be defined in the following places:
Inside a class
Outside all classes
As the top level object in a namespace
Depending on how visible we want the delegate to be, we can apply any of the
visibility modifiers to the delegate definition.
Instantiation & Invocation of Delegates
88
Once a delegate type is declared, a delegate object must be created with the new keyword
and be associated with a particular method.
When creating a delegate, the argument passed to the new expression is written similar to a
method call, but without the arguments to the method. This is known as invoking the delegate.
Syntax:
[delegate_name] [instance_name] = new [delegate_name](expression);
The delegate-name is the name of the delegate declared earlier whose object is to be
created .
The expression must be a method name or a value of a delegate-type.
If it is a method name its signature and return type must be the same as those of the
delegate.
If no matching method exists, or more than one matching method exists, an error occurs.
89
In C#, the event is a message sent by an object to indicate that particular action will
happen. The action could be caused either by a button click, mouse movements, or
other programming logic. The object that raises an event is called an event sender.
In simple words, we can say that events are used to signal user actions such as button
click, mouse over, menu selection, etc., to the user interface.
The class who raises events is called Publisher, and the class who receives the
notification is called Subscriber. There can be multiple subscribers of a single event.
Typically, a publisher raises an event when some action occurred. The subscribers,
who are interested in getting a notification when an action occurred, should register
with an event and handle it.
In C#, an event is an encapsulated delegate. It is dependent on the delegate. The
delegate defines the signature for the event handler method of the subscriber class.
102
103
In C#, events are used to enable a class or object to notify other classes or objects
about the action that is going to happen.
To declare an event, we need to use event keyword with delegate type.
An Event has no return type and it is always void.
All events are based on delegates.
All the published events must have a listening object.
Before raising an event, we need to check whether an event is subscribed or not.
By using += operator, we can subscribe to an event, and by using -= operator, we
can unsubscribe from an event.
To raise an event, we need to invoke the event delegate.
104
Keyword Description
static Makes the event available to callers at any time, even if no instance of the class exists.
virtual Allows derived classes to override the event behavior by using the override keyword.
The compiler will not generate the add and remove event accessor blocks and therefore derived classes must
abstract
provide their own implementation.
107
17-08-2021 II MCA
Exceptions
114
When we write and execute our code in the .NET framework then there is a
possibility of two types of error occurrences they are
Compilation errors
Runtime errors
The error that occurs in a program at the time of compilation is known as compilation
error (compile-time error).
These errors occur due to the syntactical mistakes under the program. That means
these errors occur by typing the wrong syntax like missing double quotes and
terminators, typing wrong spelling for keywords, assigning wrong data to a
variable, trying to create an object for abstract class and interface, etc.
Usually, this type of error occurs due to a poor understanding of the programming
language. These errors can be identified by the programmer and can be rectified
before the execution of the program only. So these errors do not cause any harm to
the program execution.
115
The errors which are occurred at the time of program execution are called the
runtime error.
These errors occurred when we are entering wrong data into a variable,
trying to open a file for which there is no permission, trying to connect to the
database with the wrong user id and password, the wrong implementation of
logic, missing required resources, etc.
A runtime error is known as an exception in C#. The exception will cause the
abnormal termination of the program execution.
Runtime errors are dangerous because whenever they occur in the program,
the program terminates abnormally on the same line where the error gets
occurred without executing the next line of code.
116
Finally: The keyword finally establishes a block that definitely executes statements placed in it.
Statements that are placed in finally block are always going to be executed irrespective of the
way the control is coming out from the try block either by completing normally or throwing an
exception by catching or not catching.
A try block must be followed by catch or finally or both blocks. The try block without a catch or
finally block will give a compile-time error.
A catch block should include a parameter of a built-in or custom exception class to get an error
detail. The following includes the Exception type parameter that catches all types of exceptions.
You can use multiple catch blocks with the different exception type parameters. This is called
exception filters. Exception filters are useful when you want to handle different types of exceptions
in different ways.
120
Once we use the try and catch blocks in our code the execution takes place
as follows:
If all the statements under try block are executed successfully, from the last
statement of the try block, the control directly jumps to the first statement that is
present after the catch block (after all catch blocks) without executing catch
block (it means there is no runtime error in the code at all ).
Then if any of the statements in the try block causes an error, from that statement
without executing any other statements in the try block, the control directly jumps
to the catch blocks which can handle that exception.
If a proper catch block is found that handles the exception thrown by the try
block, then the abnormal termination stops there, executes the code under the
catch block, and from there again it jumps to the first statement after all the
catch blocks.
If a matching catch is not found then abnormal termination occurs.
121
122
123
124
125
126
Properties of Exception Class in C#
127