DotNet Technology Complete Note BCA
DotNet Technology Complete Note BCA
]
Object Orientation; Type Safety; Memory Management; Platform Support; C# and CLR;
CLR and .NET Framework; Framework Overview; .NET Standard 2.0; Applied Technologies
Introduction to C# Language
C# is a general-purpose, object-oriented programming language. C# was developed by
Anders Hejlsberg and his team during the development of .Net Framework. It can be used
to create desktop, web and mobile applications.
C# is a hybrid of C and C++; it is a Microsoft programming language developed to compete
with Sun's Java language. C# is an object-oriented programming language used with XML-
based Web services on the .NET platform and designed for improving productivity in the
development of Web applications.
C# is an elegant and type-safe object-oriented language that enables developers to build a
variety of secure and robust applications that run on the .NET Framework. You can use C#
to create Windows client applications, XML Web services, distributed components, client-
server applications, database applications, and much, much more. Visual C# provides an
advanced code editor, convenient user interface designers, integrated debugger, and many
other tools to make it easier to develop applications based on the C# language and the
.NET Framework.
As an object-oriented language, C# supports the concepts of encapsulation, inheritance,
and polymorphism. All variables and methods, including the Main method, the
application's entry point, are encapsulated within class definitions.
The following reasons make C# a widely used professional language (Features of C#):
1. It is a modern, general-purpose programming language
2. It is object oriented.
3. It is component oriented.
4. It is easy to learn.
5. It is a structured language.
6. It produces efficient programs.
7. It can be compiled on a variety of computer platforms.
8. It is a part of .Net Framework.
Object Orientation
C# is a rich implementation of the object-orientation paradigm, which includes
encapsulation, abstraction, inheritance, and polymorphism. Encapsulation means
creating a boundary around an object, to separate its external (public) behavior from its
internal (private) implementation details.
The distinctive features of C# from an object-oriented perspective are:
1
Classes and interfaces
In a traditional object-oriented paradigm, the only kind of type is a class. In C#, there are
several other kinds of types, one of which is an interface. An interface is like a class, except
that it only describes members. The implementation for those members comes from types
that implement the interface. Interfaces are particularly useful in scenarios where multiple
inheritance is required (unlike languages such as C++ and Eiffel, C# does not support
multiple inheritance of classes).
Type Safety
C# is primarily a type-safe language, meaning that instances of types can interact only
through protocols they define, thereby ensuring each type’s internal consistency. For
instance, C# prevents you from interacting with a string type as though it were an integer
type.
More specifically, C# supports static typing, meaning that the language enforces type
safety at compile time. This is in addition to type safety being enforced at run‐ time.
Static typing eliminates a large class of errors before a program is even run. It shifts the
burden away from runtime unit tests onto the compiler to verify that all the types in a
program fit together correctly. This makes large programs much easier to manage, more
predictable, and more robust. Furthermore, static typing allows tools such as IntelliSense
in Visual Studio to help you write a program, since it knows for a given variable what type
it is, and hence what methods you can call on that variable.
C# is also called a strongly typed language because its type rules (whether enforced
statically or at runtime) are very strict. For instance, you cannot call a function that’s
2
designed to accept an integer with a floating-point number, unless you first explicitly
convert the floating-point number to an integer. This helps prevent mistakes.
Strong typing also plays a role in enabling C# code to run in a sandbox—an environment
where every aspect of security is controlled by the host. In a sandbox, it is important that
you cannot arbitrarily corrupt the state of an object by bypassing its type rules.
Memory Management
C# relies on the runtime to perform automatic memory management. The Com‐ mon
Language Runtime has a garbage collector that executes as part of your program,
reclaiming memory for objects that are no longer referenced. This frees programmers from
explicitly deallocating the memory for an object, eliminating the problem of incorrect
pointers encountered in languages such as C++.
C# does not eliminate pointers: it merely makes them unnecessary for most
programming tasks.
Platform Support
Historically, C# was used almost entirely for writing code to run on Windows platforms.
Recently, however, Microsoft and other companies have invested in other platforms,
including Linux, macOS, iOS, and Android.
Xamarin™ allows cross platform C# development for mobile applications, and Portable
Class Libraries are becoming increasingly widespread.
Microsoft’s ASP.NET Core is a cross-platform lightweight web hosting framework that can
run either on the .NET Framework or on .NET Core, an open source cross-platform runtime.
C# and CLR
C# depends on a runtime equipped with a host of features such as automatic memory
management and exception handling. At the core of the Microsoft .NET Framework is the
Common Language Runtime (CLR), which provides these runtime features. (The .NET Core
and Xamarin frameworks provide similar runtimes.)
C# is one of several managed languages that get compiled into managed code. Man‐ aged
code is represented in Intermediate Language or IL. The CLR converts the IL into the native
code of the machine, such as X86 or X64, usually just prior to execution. This is referred to
as Just-In-Time (JIT) compilation. Ahead-of-time compilation is also available to improve
start up time with large assemblies or resource constrained devices (and to satisfy iOS app
store rules when developing with Xamarin).
The container for managed code is called an assembly or portable executable. An assembly
can be an executable file (.exe) or a library (.dll), and contains not only IL, but type
information (metadata). The presence of metadata allows assemblies to reference types in
other assemblies without needing additional files.
A program can query its own metadata (reflection), and even generate new IL at runtime
(reflection.emit)
3
Introduction and Overview of .Net Framework
.NET is the framework for which we develop applications. It sits in between our application
programs and operating system.
.NET provides an object oriented environment. It ensures safe execution of the code by
performing required runtime validations. For example, it is never possible to access an
element of an array outside the boundary. Similarly, it is not possible to a program to write
into another programs area, etc. The runtime validations performed by .NET makes the
entire environment robust.
It is a programming infrastructure created by Microsoft for building, deploying, and running
applications and services that use .NET technologies, such as desktop applications and Web
services.
The .NET Framework consists of:
- the Common Language Runtime
- the Framework Class Library
4
Common Language Runtime(CLR):
CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time
environment in the .NET Framework that runs the codes and helps in making the
development process easier by providing the various services such as remoting, thread
management, type-safety, memory management, robustness etc. Basically, it is
responsible for managing the execution of .NET programs regardless of any .NET
programming language. It also helps in the management of code, as code that targets the
runtime is known as the Managed Code and code doesn’t target to runtime is known as
Unmanaged code.
The core libraries are sometimes collectively called the Base Class Library (BCL). The
entire framework is called the Framework Class Library (FCL).
5
class library includes types that support a variety of specialized development scenarios. For
example, you can use the .NET Framework to develop the following types of applications
and services:
1. Console applications
2. Windows GUI applications (Windows Forms).
3. Windows Presentation Foundation (WPF) applications.
4. ASP.NET applications.
5. Windows services.
6. Service-oriented applications using Windows Communication Foundation (WCF).
7. Workflow-enabled applications using Windows Workflow Foundation (WF).
6
Table 5-1 shows the history of compatibility between each version of C#, the CLR, and the
.NET Framework.
Other Frameworks
The Microsoft .NET Framework is the most expansive and mature framework, but runs only
on Microsoft Windows (desktop/server). Over the years, other frame‐ works have emerged
to support other platforms. There are currently three major players besides the .NET
Framework, all of which are currently owned by Microsoft:
Xamarin
For writing mobile apps that target iOS, Android, and Windows Mobile. The Xamarin
company was purchased by Microsoft in 2016.
7
Table 1-1 compares the current platform support for each of the major frameworks
Net Standard has solved all this in a different way, it provided an API specification which all
platforms should implement to remain .Net Standard complaint. This has unified the base
class libraries of different .Net platforms and has paved way to share libraries and also
brought the BCL evolution centralized as seen below.
8
.NET Standard 2.0 is a new version that significantly increases the number of APIs
compared to the previous version (1.6.1). In fact, the API surface has more than doubled
with .NET Standard 2.0.
The 1.x standards lack thousands of APIs that are present in 2.0, including much of what
we describe in this book. This can make targeting a 1.x standard significantly more
challenging, especially if you need to integrate existing code or libraries.
If you need to support older frameworks but don’t need cross platform compatibility, a
better option is to target an older version of a specific framework. In the case of Windows,
a good choice is .NET Framework 4.5 because it’s widely deployed (pre-installed on all
machines running Windows 8 and later), and it contains most of what’s in .NET Frame‐
work 4.7.
9
You can also think of .NET Standard as a lowest common denominator. In the case of .NET
Standard 2.0, the four frameworks that implement it have a similar Base Class Library, so
the lowest common denominator is big and useful. However, if you also want compatibility
with .NET Core 1.0 (with its significantly cut-down BCL), the lowest common
denominator—.NET Standard 1.x—becomes much smaller and less useful.
System Types
The most fundamental types live directly in the System namespace. These include C#’s
built-in types, the Exception base class, the Enum, Array, and Delegate base classes, and
Nullable, Type, DateTime, TimeSpan, and Guid. The System namespace also includes types
for performing mathematical functions (Math), generating random numbers (Random),
and converting between various types (Convert and Bit Converter).
Text Processing
The System.Text namespace contains the StringBuilder class (the editable or mutable
cousin of string), and the types for working with text encodings, such as UTF-8 (Encoding
and its subtypes).
The System.Text.RegularExpressions namespace contains types that perform advanced
pattern-based search-and-replace operations.
Collections
The .NET Framework offers a variety of classes for managing collections of items. These
include both list- and dictionary-based structures, and work in conjunction with a set of
standard interfaces that unify their common characteristics. All collection types are defined
in the following namespaces:
Queries
Language Integrated Query (LINQ) was added in Framework 3.5. LINQ allows you to
perform type-safe queries over local and remote collections (e.g., SQL Server tables). A big
advantage of LINQ is that it presents a consistent querying API across a variety of domains.
The essential types reside in the following namespaces, and are part of .NET Standard 2.0:
10
XML
XML is used widely within the .NET Framework, and so is supported extensively. The XML
name‐ spaces are:
Diagnostics
Diagnostics refers to .NET’s logging and assertion facilities and describe how to interact
with other processes, write to the Windows event log, and use performance counters for
monitoring. The types for this are defined in and under System.Diagnostics. Windows-
specific features are not part of .NET Standard, and are avail‐ able only in the .NET
Framework.
Networking
You can directly access standard network protocols such as HTTP, FTP, TCP/IP, and SMTP
via the types in System.Net.
The latter two namespaces are unavailable to Windows Store applications if you’re
targeting Windows 8/8.1 (WinRT), but are available to Windows 10 Store apps (UWP) as
part of the .NET Standard 2.0 contract. For WinRT apps, use third-party libraries for sending
mail, and the WinRT types in Windows.Networking.Sockets for working with sockets.
Serialization
The Framework provides several systems for saving and restoring objects to a binary or
text representation. Such systems are required for distributed application technologies,
11
such as WCF, Web Services, and Remoting, and also to save and restore objects to a file.
The types for serialization reside in the following namespaces:
Dynamic Programming
Dynamic Language Runtime, which has been a part of the CLR since Framework 4.0. The
types for dynamic programming are in System.Dynamic.
Security
Code access, role, and identity security, and the transparency model introduced in CLR 4.0.
Cryptography can be done in the Framework, covering encryption, hashing, and data
protection. The types for this are defined in:
System.Security
System.Security.Permissions
System.Security.Policy
System.Security.Cryptography
Advanced Threading
C#’s asynchronous functions make concurrent programming significantly easier because
they lessen the need for lower-level techniques. However, there are still times when you
need signaling constructs, thread-local storage, reader/writer locks, and so on. Threading
types are in the System.Threading namespace.
12
Applied Technologies
Descriptions of .NET Implementations
User-Interface APIs
User-interface–based applications can be divided into two categories: thin client, which
amounts to a website, and rich client, which is a program the end user must download and
install on a computer or mobile device.
For thin client applications, .NET provides ASP.NET and ASP.NET Core.For rich-client
applications that target Windows 7/8/10 desktop, .NET provides the WPF and Windows
Forms APIs. For rich-client apps that target iOS, Android, and Windows Phone, there’s
Xamarin, and for writing rich-client store apps for Win‐ dows 10 desktop and devices.
Finally, there’s a hybrid technology called Silverlight, which has been largely abandoned
since the rise of HTML5.
ASP.NET
Applications written using ASP.NET host under Windows IIS and can be accessed from any
web browser. Here are the advantages of ASP.NET over rich-client technologies:
• There is zero deployment at the client end.
• Clients can run a non-Windows platform.
• Updates are easily deployed.
In writing your web pages, you can choose between the traditional Web Forms and the
newer MVC (Model-View-Controller) API. Both build on the ASP.NET infra‐ structure. Web
Forms has been part of the Framework since its inception; MVC was written much later in
response to the success of Ruby on Rails and MonoRail. It provides, in general, a better
programming abstraction than Web Forms; it also allows more control over the generated
HTML.
13
ASP.NET Core
A relatively recent addition, ASP.NET Core is similar to ASP.NET, but runs on both .NET
Framework and .NET Core (allowing for cross-platform deployment). ASP.NET Core
features a lighter-weight modular architecture, with the ability to self-host in a custom
process, and an open source license. Unlike its predecessors, ASP.NET Core is not
dependent on System.Web and the historical baggage of Web Forms. It’s particularly
suitable for micro-services and deployment inside containers.
Windows Forms
Windows Forms is a rich-client API that’s as old as the .NET Framework. Com‐ pared to
WPF, Windows Forms is a relatively simple technology that provides most of the features
you need in writing a typical Windows application. It also has significant relevancy in
maintaining legacy applications. It has a number of drawbacks, though, compared to WPF:
• Controls are positioned and sized in pixels, making it easy to write applications that
break on clients whose DPI settings differ from the developer’s (although this has
improved somewhat in Framework 4.7).
• The API for drawing nonstandard controls is GDI+, which, although reasonably
flexible, is slow in rendering large areas (and without double buffering, may flicker).
• Controls lack true transparency.
• Most controls are non-compositional. For instance, you can’t put an image control
inside a tab control header. Customizing list views and combo boxes is time-
consuming and painful.
• Dynamic layout is difficult to get right reliably
Xamarin
Xamarin, now owned by Microsoft, lets you write mobile apps in C# that target iOS and
Android, as well as Windows Phone. Being cross-platform, this runs not on the .NET
Framework, but its own framework (a derivation of the open source Mono framework).
14
UWP (Universal Windows Platform)
UWP is for writing apps that target Windows 10 desktop and devices, distributed via the
Windows Store. Its rich-client API is designed for writing touch-first user interfaces, and
was inspired by WPF and uses XAML for layout. The namespaces are Windows.UI and
Windows.UI.Xaml.
Silverlight
Silverlight is also distinct from the .NET Framework, and lets you write a graphical UI that
runs in a web browser, much like Macromedia’s Flash. With the rise of HTML5, Microsoft
has abandoned Silverlight.
Backend Technologies
ADO.NET
ADO.NET is the managed data access API. Although the name is derived from the 1990s-
era ADO (ActiveX Data Objects), the technology is completely different. ADO.NET contains
two major low-level components:
Provider layer
The provider model defines common classes and interfaces for low-level access to database
providers. These interfaces comprise connections, commands, adapters, and readers
(forward-only, read-only cursors over a database). The Framework ships with native
support for Microsoft SQL Server, and numerous third-party drivers are available for other
databases.
DataSet model
A DataSet is a structured cache of data. It resembles a primitive in-memory database, which
defines SQL constructs such as tables, rows, columns, relationships, constraints, and views.
By programming against a cache of data, you can reduce the number of trips to the server,
increasing server scalability and the responsiveness of a rich-client user interface. DataSets
are serializable and are designed to be sent across the wire between client and server
applications.
Sitting above the provider layer are three APIs that offer the ability to query databases via
LINQ:
• Entity Framework (.NET Framework only)
• Entity Framework Core (.NET Framework and .NET Core)
• LINQ to SQL (.NET Framework only)
LINQ to SQL is simpler than Entity Framework, and has historically produced better SQL
(although Entity Framework has benefited from numerous updates).
Entity Framework is more flexible in that you can create elaborate mappings between the
database and the classes that you query (Entity Data Model), and offers a model that allows
third-party support for databases other than SQL Server.
15
Entity Framework Core (EF Core) is a rewrite of Entity Framework with a simpler design
inspired by LINQ to SQL. It abandons the complex Entity Data Model and runs on both .NET
Framework and .NET Core.
WCF further decouples the client and server through service contracts and data contracts.
Conceptually, the client sends an (XML or binary) message to an end‐ point on a remote
service, rather than directly invoking a remote method. One of the benefits of this
decoupling is that clients have no dependency on the .NET plat‐ form or on any proprietary
communication protocols.
For .NET-to-.NET communication, however, WCF offers richer serialization and better
tooling than with REST APIs. It’s also potentially faster as it’s not tied to HTTP and can use
binary serialization.
The types for communicating with WCF are in, and below, the System.Service Model
namespace.
16
Web API
Web API runs over ASP.NET/ASP.NET Core and is architecturally similar to Microsoft’s MVC
API, except that it’s designed to expose services and data instead of web pages. Its
advantage over WCF is in allowing you to follow popular REST over HTTP conventions,
offering easy interoperability with the widest range of platforms.
REST implementations are internally simpler than the SOAP and WS- protocols that WCF
relies on for interoperability. REST APIs are also architecturally more elegant for loosely-
coupled systems, building on de-facto standards and making excellent use of what HTTP
already provides.
Its growing popularity has made it the first choice of many experienced and fresher and
now one can think of having a great career start in this field outside India too. .Net is now
part of many international markets like USA, UAE, South Africa, UK and other developing
countries and is heading forward with each passing day. With its every new version .Net
technologies is evolving at a fast pace and creating amazing job opportunities for the
developers.
The availability of RAD in.Net, which means the Rapid Application Development is the
reason behind its success. The plus point of learning this technology is that you can develop
as many applications as you want for different platforms and environments. You can even
use it for building XML web applications and web services that can excellently run on the
Internet. .Net is best suited for developing window based applications, web server
programs and applications, which are both PC and mobile compatible. It’s easy to transfer
feature is what makes it the popular choice.
The biggest advantage of learning .net is that one can get a job in various profiles like
he/she can be absorbed as a software developer also or a.Net technician too. Today, there
are an array of institutes and firms that offer certified and short term course in .Net, which
17
is a great move from career point of view. Whether you are a diploma holder or an Engineer
or an MCA, learning .Net will surely set your career and will offer it a right pace and track.
There are ample of career options in this particular field. An interested candidate can go
for MCTS(VB.net), MCTS(ASP.net) and MCPD, which are some of the international
certifications. You can even choose from Cisco certifications like CCNA, CCNP, CCIE, which
will give a new direction to your career.
With so many job prospects in this technology, choosing it will be an ideal choice for your
career. This clearly illustrates the future scope of .Net, which is sure to offer you great
future ahead in almost all the spheres, ranging from Desktop applications to mobile
applications.
18
Procedure-Oriented vs. Object-Oriented Programming
Object-Oriented Programming (OOP) is a high-level programming language where a
program is divided into small chunks called objects using the object-oriented model, hence
the name. This paradigm is based on objects and classes.
• Object – An object is basically a self-contained entity that accumulates both data
and procedures to manipulate the data. Objects are merely instances of classes.
• Class – A class, in simple terms, is a blueprint of an object which defines all the
common properties of one or more objects that are associated with it. A class can
be used to define multiple objects within a program.
The OOP paradigm mainly eyes on the data rather than the algorithm to create modules
by dividing a program into data and functions that are bundled within the objects. The
modules cannot be modified when a new object is added restricting any non-member
function access to the data. Methods are the only way to assess the data.
Objects can communicate with each other through same member functions. This process
is known as message passing. This anonymity among the objects is what makes the
program secure. A programmer can create a new object from the already existing objects
by taking most of its features thus making the program easy to implement and modify.
19
In POP, Most function uses Global data for In OOP, data cannot move easily from function
sharing that can be accessed freely from to function, it can be kept public or private so
function to function in the system. we can control the access of data.
POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure. security.
In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator
Overloading.
Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET,
C#.NET.
20
Unit -2 C# Language Basics [12 Hrs]
Writing Console and GUI Applications; Identifiers and keywords; Writing comments; Data
Types; Expressions and Operators; Strings and Characters; Arrays; Variables and
Parameters; Statements (Declaration, Expression, Selection, Iteration and Jump
Statements); Namespaces
A First C# Program
Here is a program that multiplies 12 by 30 and prints the result, 360, to the screen. The
double forward slash indicates that the remainder of a line is a comment
Writing higher-level functions that call upon lower-level functions simplifies a pro‐ gram.
We can refactor our program with a reusable method that multiplies an integer by 12 as
follows:
Compilation
The C# compiler compiles source code, specified as a set of files with the .cs extension, into
an assembly. An assembly is the unit of packaging and deployment in .NET. An assembly
can be either an application or a library. A normal console or Windows application has a
Main method and is an .exe file.
A library is a .dll and is equivalent to an .exe without an entry point. Its purpose is to be
called upon (referenced) by an application or by other libraries. The .NET Framework is a
set of libraries.
21
The name of the C# compiler is csc.exe. You can either use an IDE such as Visual Studio to
compile, or call csc manually from the command line.
To compile manually, first save a program to a file such as MyFirstProgram.cs, and then go
to the command line and invoke csc (located in
C:\Windows\Microsoft.NET\Framework\v4.0.30319) as follows:
csc MyFirstProgram.cs
This produces an application named MyFirstProgram.exe
Keywords are names that mean something special to the compiler. These are the keywords
in our example program:
Most keywords are reserved, which means that you can’t use them as identifiers. Here is
the full list of C# reserved keywords (Total 77):
22
Avoiding conflicts
If you really want to use an identifier that clashes with a reserved keyword, you can do so
by qualifying it with the @ prefix. For instance:
The @ symbol doesn’t form part of the identifier itself. So @myVariable is the same as
myVariable.
Contextual keywords
Some keywords are contextual, meaning they can also be used as identifiers— without an
@ symbol. These are:
An operator transforms and combines expressions. Most operators in C# are denoted with
a symbol, such as the multiplication operator, *. We will discuss operators in more detail
later in this chapter. These are the operators we used in our example program:
A period denotes a member of something (or a decimal point with numeric literals).
Parentheses are used when declaring or calling a method; empty parentheses are used
when the method accepts no arguments.
An equals sign performs assignment. (The double equals sign, ==, performs equality
comparison).
23
Comments
C# offers two different styles of source-code documentation: single-line comments and
multiline comments. A single-line comment begins with a double forward slash and
continues until the end of the line. For example:
Type Basics
A type defines the blueprint for a value. In our example, we used two literals of type int
with values 12 and 30. We also declared a variable of type int whose name was x:
A variable denotes a storage location that can contain different values over time. In
contrast, a constant always represents the same value.
All values in C# are instances of a type. The meaning of a value, and the set of possible
values a variable can have, is determined by its type.
Another predefined C# type is string. The string type represents a sequence of characters,
such as “.NET” or “http://oreilly.com”. We can work with strings by calling functions on
them as follows:
24
The predefined bool type has exactly two possible values: true and false. The bool type is
commonly used to conditionally branch execution flow based with an if statement. For
example:
In C#, predefined types (also referred to as built-in types) are recognized with a C#
keyword. The System namespace in the .NET Framework contains many important types
that are not predefined by C# (e.g., DateTime).
A type contains data members and function members. The data member of UnitConverter
is the field called ratio. The function members of UnitConverter are the Convert method
and the UnitConverter’s constructor.
25
Conversions
C# can convert between instances of compatible types. A conversion always creates a new
value from an existing one. Conversions can be either implicit or explicit: implicit
conversions happen automatically, and explicit conversions require a cast.
In the following example, we implicitly convert an int to a long type (which has twice the
bitwise capacity of an int) and explicitly cast an int to a short type (which has half the
capacity of an int):
Implicit conversions are allowed when both of the following are true:
• The compiler can guarantee they will always succeed.
• No information is lost in conversion.
Conversely, explicit conversions are required when one of the following is true:
• The compiler cannot guarantee they will always succeed.
• Information may be lost during conversion.
Value types comprise most built-in types (specifically, all numeric types, the char type, and
the bool type) as well as custom struct and enum types.
Reference types comprise all class, array, delegate, and interface types. (This includes the
predefined string type.)
The fundamental difference between value types and reference types is how they are
handled in memory.
Value types
The content of a value type variable or constant is simply a value. For example, the content
of the built-in value type, int, is 32 bits of data.
You can define a custom value type with the struct keyword:
26
The assignment of a value-type instance always copies the instance. For example:
Reference types
A reference type is more complex than a value type, having two parts: an object and the
reference to that object. The content of a reference-type variable or constant is a reference
to an object that contains the value. Here is the Point type from our previous example
rewritten as a class, rather than a struct.
27
Numeric Types
C# has the predefined numeric types:
Numeric Conversions
Converting between integral types
Integral type conversions are implicit when the destination type can represent every
possible value of the source type. Otherwise, an explicit conversion is required. For
example:
28
When you cast from a floating-point number to an integral type, any fractional portion is
truncated; no rounding is per‐ formed. The static class System.Convert provides methods
that round while converting between various numeric types.
Implicitly converting a large integral type to a floating-point type preserves magnitude but
may occasionally lose precision. This is because floating-point types always have more
magnitude than integral types, but may have less precision. Rewriting our example with a
larger number demonstrates this:
Decimal conversions
All integral types can be implicitly converted to the decimal type, since a decimal can
represent every possible C# integral-type value. All other numeric conversions to and from
a decimal type must be explicit.
Operators in C #:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Miscellaneous Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable
A holds 10 and variable B holds 20 then:
29
Relational Operators
Following table shows all the relational operators supported by C#. Assume
variable A holds 10 and variable B holds 20, then:
== Checks if the values of two operands are equal or not, if yes then (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not, if values are (A != B)
not equal then condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (A > B) is
operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of right (A < B) is
operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand, if yes then condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value (A <= B)
of right operand, if yes then condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value true and variable B holds Boolean value false, then:
&& Called Logical AND operator. If both the operands are non zero then (A && B)
condition becomes true. is false.
30
! Called Logical NOT Operator. Use to reverses the logical state of its !(A &&
operand. If a condition is true then Logical NOT operator will make B) is
false. true.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The Bitwise operators
supported by C# are listed in the following table. Assume variable A holds 60 and variable
B holds 13, then:
& Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12,
operands. which is
0000 1100
^ Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49,
not both. which is
0011 0001
~ Binary Ones Complement Operator is unary and has the effect (~A ) = 61,
of 'flipping' bits. which is
1100 0011 in
2's
complement
due to a
signed
binary
number.
<< Binary Left Shift Operator. The left operands value is moved left A << 2 = 240,
by the number of bits specified by the right operand. which is
1111 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15,
right by the number of bits specified by the right operand. which is
0000 1111
31
Assignment Operators
There are following assignment operators supported by C#:
32
&= Bitwise AND assignment operator C &= 2 is
same as C
=C&2
Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? :supported by C#.
as Cast without raising an exception if the cast fails. Object obj = new
StringReader("Hello");
StringReader r = obj as
StringReader;
33
Conditional operator (ternary operator)
The conditional operator (more commonly called the ternary operator, as it’s the only
operator that takes three operands) has the form q ? a : b, where if condition q is true, a is
evaluated, else b is evaluated. For example:
The \u (or \x) escape sequence lets you specify any Unicode character via its four-digit
hexadecimal code:
34
Char Conversions
An implicit conversion from a char to a numeric type works for the numeric types that can
accommodate an unsigned short. For other numeric types, an explicit conversion is
required.
String Type
C#’s string type (aliasing the System.String type) represents an immutable sequence of
Unicode characters. A string literal is specified inside double quotes:
The cost of this is that whenever you need a literal backslash, you must write it twice:
To avoid this problem, C# allows verbatim string literals. A verbatim string literal is prefixed
with @ and does not support escape sequences. The following verbatim string is identical
to the preceding one:
String concatenation
The + operator concatenates two strings:
One of the operands may be a non-string value, in which case ToString is called on that
value. For example:
Using the + operator repeatedly to build up a string is inefficient: a better solution is to use
the System.Text.StringBuilder type.
35
String interpolation
A string preceded with the $ character is called an interpolated string. Interpolated strings
can include expressions inside braces:
String comparisons
string does not support < and > operators for comparisons. You must use the string’s
CompareTo method.
Arrays
An array represents a fixed number of variables (called elements) of a particular type. The
elements in an array are always stored in a contiguous block of memory, providing highly
efficient access.
An array is denoted with square brackets after the element type. For example:
Square brackets also index the array, accessing a particular element by position:
This prints “e” because array indexes start at 0. We can use a for loop statement to iterate
through each element in the array. The for loop in this example cycles the integer i from 0
to 4:
An array initialization expression lets you declare and populate an array in a single step:
Multidimensional Arrays
Multidimensional arrays come in two varieties: rectangular and jagged.
Rectangular arrays represent an n-dimensional block of memory, and jagged arrays are
arrays of arrays.
Rectangular arrays
Rectangular arrays are declared using commas to separate each dimension. The following
declares a rectangular two-dimensional array, where the dimensions are 3 by 3:
36
A rectangular array can be initialized as follows (to create an array identical to the previous
example):
Example Program,
Jagged arrays
Jagged arrays are declared using successive square brackets to represent each dimension.
Here is an example of declaring a jagged two-dimensional array, where the outermost
dimension is 3:
The inner dimensions aren’t specified in the declaration because, unlike a rectangular
array, each inner array can be an arbitrary length. Each inner array is implicitly initialized
to null rather than an empty array.
A jagged array can be initialized as follows (to create an array identical to the previous
example with an additional element at the end):
37
Example Program,
38
Bounds Checking
All array indexing is bounds-checked by the runtime. An IndexOutOfRangeException is
thrown if you use an invalid index:
As with Java, array bounds checking is necessary for type safety and simplifies debugging.
Generally, the performance hit from bounds checking is minor, and the JIT (Just-In-Time)
compiler can perform optimizations, such as determining in advance whether all indexes
will be safe before entering a loop, thus avoiding a check on each iteration. In addition, C#
provides “unsafe” code that can explicitly bypass bounds checking.
This method is recursive, meaning that it calls itself. Each time the method is entered, a
new int is allocated on the stack, and each time the method exits, the int is deallocated.
Heap
The heap is a block of memory in which objects (i.e., reference-type instances) reside.
Whenever a new object is created, it is allocated on the heap, and a reference to that object
is returned. During a program’s execution, the heap starts filling up as new objects are
created. The runtime has a garbage collector that periodically deallocates objects from the
heap, so your program does not run out of memory. An object is eligible for deallocation
as soon as it’s not referenced by anything that’s itself “alive.”
39
Value-type instances (and object references) live wherever the variable was declared. If
the instance was declared as a field within a class type, or as an array element, that instance
lives on the heap.
Definite Assignment
C# enforces a definite assignment policy. In practice, this means that outside of an unsafe
context, it’s impossible to access uninitialized memory. Definite assignment has three
implications:
• Local variables must be assigned a value before they can be read.
• Function arguments must be supplied when a method is called (unless marked as
optional.
• All other variables (such as fields and array elements) are automatically initialized
by the runtime.
Fields and array elements are automatically initialized with the default values for their type.
The following code outputs 0, because array elements are implicitly assigned to their
default values:
40
The following code outputs 0, because fields are implicitly assigned a default value:
Default Values
All type instances have a default value. The default value for the predefined types is the
result of a bitwise zeroing of memory:
You can obtain the default value for any type with the default keyword,
Parameters
A method has a sequence of parameters. Parameters define the set of arguments that must
be provided for that method. In this example, the method Foo has a single parameter
named p, of type int:
You can control how parameters are passed with the ref and out modifiers:
41
Passing arguments by value
By default, arguments in C# are passed by value, which is by far the most common case.
This means a copy of the value is created when passed to the method:
Assigning p a new value does not change the contents of x, since p and x reside in different
memory locations.
42
The out modifier
The out modifier is most commonly used to get multiple return values back from a method.
For example:
Optional parameters
A parameter is optional if it specifies a default value in its declaration:
43
Operator Precedence and Associativity
When an expression contains multiple operators, precedence and associativity determine
the order of their evaluation. Operators with higher precedence execute before operators
of lower precedence. If the operators have the same precedence, the operator’s
associativity determines the order of evaluation.
Left-associative operators
Binary operators (except for assignment, lambda, and null coalescing operators) are left-
associative; in other words, they are evaluated from left to right. For example, the following
expression:
Right-associative operators
The assignment operators, lambda, null coalescing, and conditional operator are right-
associative; in other words, they are evaluated from right to left. Right associativity allows
multiple assignments such as the following to compile:
Null Operators
C# provides two operators to make it easier to work with nulls: the null coalescing operator
and the null-conditional operator.
44
Null-conditional Operator
The ?. operator is the null-conditional or “Elvis” operator. It allows you to call methods and
access members just like the standard dot operator, except that if the operand on the left
is null, the expression evaluates to null instead of throwing a NullReferenceException:
Statements
Functions comprise statements that execute sequentially in the textual order in which they
appear. A statement block is a series of statements appearing between braces (the {}
tokens).
Declaration Statements
A declaration statement declares a new variable, optionally initializing the variable with an
expression. A declaration statement ends in a semicolon. You may declare multiple
variables of the same type in a comma-separated list. For example:
A constant declaration is like a variable declaration, except that it cannot be changed after
it has been declared, and the initialization must occur with the declaration.
Local variables
The scope of a local variable or local constant extends throughout the current block. You
cannot declare another local variable with the same name in the current block or in any
nested blocks. For example:
45
Expression Statements
Expression statements are expressions that are also valid statements. An expression
statement must either change state or call something that might change state.
Changing state essentially means changing a variable. The possible expression statements
are:
• Assignment expressions (including increment and decrement expressions)
• Method call expressions (both void and non-void)
• Object instantiation expressions
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide, which value should be assigned to the variable. The operator is written as –
Following is an example –
46
Control Statements
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. C# program control
statements can be put into the following categories: selection, iteration, and jump.
- Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable.
- Iteration statements enable program execution to repeat one or more statements
(that is, iteration statements form loops).
- Jump statements allow your program to execute in a nonlinear fashion.
if
The if statement is C#’s conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
The if works like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed. In no case will both statements be executed. For
example, consider the following:
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are they
both set to zero.
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else. Here is an example:
47
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-
else-if ladder. It looks like this:
Here is a program that uses an if-else-if ladder to determine which season a particular
month is in.
switch
The switch statement is C#’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As
such, it often provides a better alternative than a large series of if-else-if statements. Here
is the general form of a switch statement:
48
Here is a simple example that uses a switch statement:
Iteration Statements
C#’s iteration statements are for, while, do-while and for-each loop. These statements
create what we commonly call loops. As you probably know, a loop repeatedly executes
the same set of instructions until a termination condition is met. A loop statement allows
us to execute a statement or group of statements multiple times.
49
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to be executed a specific number of times. A for loop is useful when you know how
many times a task is to be repeated.
The syntax of a for loop is –
while Loop
A while loop statement in C# programming language repeatedly executes a target
statement as long as a given condition is true.
The syntax of a while loop is –
Here, key point of the while loop is that the loop might not ever run. When the expression
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.
50
Example:
do while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Following is the syntax of a do...while loop –
Example
51
foreach Loop
The foreach statement iterates over each element in an enumerable object. Most of the
types in C# and the .NET Framework that represent a set or list of elements are
enumerable. For example, both an array and a string are enumerable. Here is an example
of enumerating over the characters in a string, from the first character through to the last:
Output:
10
20
30
40
50
52
Nested Loops
Like all other programming languages, C# allows loops to be nested. That is, one loop may
be inside another. For example, here is a program that nests for loops:
Jump Statements
The C# jump statements are break, continue, goto, return, and throw. These statements
transfer control to another part of your program.
Using break
In C#, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used
as a “civilized” form of goto.
53
As you can see, although the for loop is designed to run from 0 to 99, the break statement
causes it to terminate early, when i equals 10.
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for
this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s
end. The continue statement performs such an action.
In a while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop. In a for loop, control goes first
to the iteration portion of the for statement and then to the conditional expression. For all
three loops, any intermediate code is bypassed.
Here is an example program that uses continue to cause two numbers to be printed on
each line:
54
Using return
The last control statement is return. The return statement is used to explicitly return from
a method. That is, it causes program control to transfer back to the caller of the method.
As such, it is categorized as a jump statement.
Example:
Output:
Sum of two numbers=25
A label is a placeholder in a code block that precedes a statement, denoted with a colon
suffix. The following iterates the numbers 1 through 5, mimicking a for loop:
55
The throw statement
The throw statement throws an exception to indicate an error has occurred.
If(age<18)
throw new ArithmeticExcecption(“Not Eligible to Vote”);
Namespaces
A namespace is a domain for type names. Types are typically organized into hierarchical
namespaces, making them easier to find and avoiding conflicts. For example, the RSA type
that handles public key encryption is defined within the following namespace:
The namespace keyword defines a namespace for types within that block. For example:
The dots in the namespace indicate a hierarchy of nested namespaces. The code that
follows is semantically identical to the preceding example:
56
using static
From C# 6, you can import not just a namespace, but a specific type, with the using static
directive. All static members of that type can then be used without being qualified with the
type name. In the following example, we call the Console class’s static WriteLine method:
Name hiding
If the same type name appears in both an inner and an outer namespace, the inner name
wins. To refer to the type in the outer namespace, you must qualify its name. For example:
57
Repeated namespaces
You can repeat a namespace declaration, as long as the type names within the namespaces
don’t conflict:
We can even break the example into two source files such that we could compile each class
into a different assembly.
58
Advanced Namespace Features
Extern
Extern aliases allow your program to reference two types with the same fully qualified
name (i.e., the namespace and type name are identical). This is an unusual scenario and
can occur only when the two types come from different assemblies. Consider the following
example.
The application cannot compile, because Widget is ambiguous. Extern aliases can resolve
the ambiguity in our application:
}}
59
Unit -3 Creating Types in C# [12 Hrs]
Classes; Constructors and Destructors; this Reference; Properties; Indexers; Static
Constructors and Classes; Finalizers; Dynamic Binding; Operator Overloading;
Inheritance; Abstract Classes and Methods; base Keyword; Overloading; Object Type;
Structs; Access Modifiers; Interfaces; Enums; Generics
Classes
A class, in the context of C#, are templates that are used to create objects, and to define
object data types and methods. Core properties include the data types and methods that
may be used by the object. All class objects should have the basic class properties. Classes
are categories, and objects are items within each category.
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the (:). A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class,
if any, preceded by the (:). A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Object
An object is a combination of data and procedures working on the available data. An object
has a state and behavior. The state of an object is stored in fields (variables), while methods
60
(functions) display the object's behavior. Objects are created from templates known as
classes. In C#, an object is created using the keyword "new". Object is an instance of a class.
There are three steps to creating a Java object:
1. Declaration of the object
2. Instantiation of the object
3. Initialization of the object
When a object is declared, a name is associated with that object. The object is instantiated
so that memory space can be allocated. Initialization is the process of assigning a proper
initial value to this allocated space. The properties of Java objects include:
• One can only interact with the object through its methods. Hence, internal details
are hidden.
• When coding, an existing object may be reused.
• When a program's operation is hindered by a particular object, that object can be
easily removed and replaced.
A new object t from the class "tree" is created using the following syntax:
Tree t = new Tree ().
Fields
A field is a variable that is a member of a class or struct. For example:
class Octopus
{
string name;
public int Age = 10;
}
61
Methods
A method performs an action in a series of statements. A method can receive input data
from the caller by specifying parameters and output data back to the caller by specifying a
return type. A method can specify a void return type, indicating that it doesn’t return any
value to its caller.
A method can also output data back to the caller via ref/out parameters. A method’s
signature must be unique within the type. A method’s signature com‐ prises its name and
parameter types in order (but not the parameter names, nor the return type).
Expression-bodied methods
A method that comprises a single expression, such as the following:
int Foo (int x) { return x * 2; }
can be written more tersely as an expression-bodied method. A fat arrow replaces the
braces and return keyword:
int Foo (int x) => x * 2;
Expression-bodied functions can also have a void return type:
void Foo (int x) => Console.WriteLine (x);
Overloading methods
A type may overload methods (have multiple methods with the same name), as long as
the signatures are different. For example, the following methods can all coexist in the same
type:
However, the following pairs of methods cannot coexist in the same type, since the return
type and the params modifier are not part of a method’s signature:
62
Constructors
A constructor in C# is a block of code similar to a method that’s called when an instance of
an object is created. Here are the key differences between a constructor and a method:
• A constructor doesn’t have a return type.
• The name of the constructor must be the same as the name of the class.
• Unlike methods, constructors are not considered members of a class.
• A constructor is called automatically when a new instance of an object is created.
All classes have constructors, whether you define one or not, because C# automatically
provides a default constructor that initializes all member variables to zero. However, once
you define your own constructor, the default constructor is no longer used.
Default Constructor
The default constructor is a constructor that is automatically generated in the absence of
explicit constructors (i.e. no user defined constructor). The automatically provided
constructor is called sometimes a nullary constructor.
Following is the syntax of a default constructor –
Instance Constructors
Constructors run initialization code on a class or struct. A constructor is defined like a
method, except that the method name and return type are reduced to the name of the
enclosing type:
63
Overloaded Constructors
A class or struct may overload constructors. To avoid code duplication, one constructor
may call another, using this keyword:
When one constructor calls another, the called constructor executes first.
Destructor
Destructors in C# are methods inside the class used to destroy instances of that class when
they are no longer needed. The Destructor is called implicitly by the .NET Framework’s
Garbage collector and therefore programmer has no control as when to invoke the
destructor. An instance variable or an object is eligible for destruction when it is no longer
reachable.
Important Points:
• A Destructor is unique to its class i.e. there cannot be more than one destructor in
a class.
• A Destructor has no return type and has exactly the same name as the class name
(Including the same case).
• It is distinguished apart from a constructor because of the Tilde symbol (~) prefixed
to its name.
• A Destructor does not accept any parameters and modifiers.
• It cannot be defined in Structures. It is only used with classes.
• It cannot be overloaded or inherited.
• It is called when the program exits.
• Internally, Destructor called the Finalize method on the base class of object.
Syntax
64
Example:
class ConsDes
{
//constructor
public ConsDes(string message)
{
Console.WriteLine(message);
}
//destructor
~ConsDes()
{
Console.WriteLine("This is a destructor");
Console.ReadKey();
}
}
class Construct
{
static void Main(string[] args)
{
string msg = "This is a constructor";
ConsDes obj = new ConsDes(msg);
obj.test();
}
}
Output:
This is a constructor
This is a method
This is a destructor
Static Constructor
In c#, Static Constructor is used to perform a particular action only once throughout the
application. If we declare a constructor as static, then it will be invoked only once
irrespective of number of class instances and it will be called automatically before the first
instance is created.
Generally, in c# the static constructor will not accept any access modifiers and parameters.
In simple words we can say it’s a parameter less.
65
• The static constructor will invoke automatically, whenever we create a first instance
of class.
• The static constructor will be invoked by CLR so we don’t have a control on static
constructor execution order in c#.
• In c#, only one static constructor is allowed to create.
Example
class User
{
// Static Constructor
static User()
{
Console.WriteLine("I am Static Constructor");
}
// Default Constructor
public User()
{
Console.WriteLine("I am Default Constructor");
}
}
class Program
{
static void Main(string[] args)
{
// Both Static and Default constructors will invoke for
first instance
User user = new User();
// Only Default constructor will invoke
User user1 = new User();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
66
The this Reference
The “this” keyword in C# is used to refer to the current instance of the class. It is also used
to differentiate between the method parameters and class fields if they both have the
same name.
Another usage of “this” keyword is to call another constructor from a constructor in the
same class.
Here, for an example, we are showing a record of Students i.e: id, Name, Age, and Subject.
To refer to the fields of the current class, we have used the “this” keyword in C#:
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
this.subject = subject;
this.age = age;
}
Let us see the complete example to learn how to work with the “this” keyword in C#:
using System;
class Student {
public int id, age;
public String name, subject;
class StudentDetails {
public static void Main(string[] args) {
Student std1 = new Student(001, "Jack", 23, "Maths");
std1.showInfo();
}
}
Output:
001 Jack 23 Maths
67
Properties
Properties look like fields from the outside, but internally they contain logic, like methods
do. Properties are named members of classes, structures, and interfaces. Member
variables or methods in a class or structures are called Fields. Properties are an extension
of fields and are accessed using the same syntax. They use accessors(get and set) through
which the values of the private fields can be read, written or manipulated.
Usually, inside a class, we declare a data field as private and will provide a set of public SET
and GET methods to access the data fields. This is a good programming practice since the
data fields are not directly accessible outside the class. We must use the set/get methods
to access the data fields.
Output:
10
Automatic Properties
he most common implementation for a property is a getter and/or setter that sim‐ ply
reads and writes to a private field of the same type as the property. An automatic property
declaration instructs the compiler to provide this implementation. We can improve the first
example in this section by declaring CurrentPrice as an auto‐ matic property:
68
class Chk
{
public int a { get;set;}
public int b { get; set; }
public int sum
{
get { return a + b; }
}
class Test
{
static void Main()
{
Chk obj = new Chk();
obj.a = 10;
obj.b = 5;
Console.WriteLine("Sum of "+obj.a+" and "+obj.b+" = "+obj.sum);
Console.ReadKey();
}
}
Output:
Sum of 10 and 5 = 15
Indexers
Indexers provide a natural syntax for accessing elements in a class or struct that
encapsulate a list or dictionary of values. Indexers are similar to properties, but are
accessed via an index argument rather than a property name.
The string class has an indexer that lets you access each of its char values via an int index:
C# indexers are usually known as smart arrays. A C# indexer is a class property that allows
you to access a member variable of a class or struct using the features of an array. In C#,
indexers are created using this keyword. Indexers in C# are applicable on both classes and
structs.
Defining an indexer allows you to create a class like that can allows its items to be accessed
an array. Instances of that class can be accessed using the [] array access operator.
69
In the above code:
<modifier>
can be private, public, protected or internal.
<return type>
can be any valid C# types.
this
this is a special keyword in C# to indicate the object of the current class.
[argument list]
The formal-argument-list specifies the parameters of the indexer.
70
Difference between Indexers and Properties
71
Static Classes
A C# static class is a class that can't be instantiated. The sole purpose of the class is to
provide blueprints of its inherited classes. A static class is created using the "static"
keyword in C#. A static class can contain static members only. You can‘t create an object
for the static class.
72
Example of static class
Output
The details of Author is:
Author name : Ankita
Language : CSharp
Total number of articles : 84
Finalizers
Finalizers are class-only methods that execute before the garbage collector reclaims the
memory for an unreferenced object. The syntax for a finalizer is the name of the class
prefixed with the ~ symbol:
73
Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the
mechanism in java by which one class is allow to inherit the features (fields and methods)
of another class.
The process by which one class acquires the properties (data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance is to
provide the reusability of code so that a class has to write only the unique features and rest
of the common properties and functionalities can be extended from the another class.
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.
Inheritance represents the IS-A relationship which is also known as a parent- child
relationship. Inheritance is used in java for the following:
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Types of inheritance in C#
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In C# programming, multiple and hybrid inheritance is supported through interface only.
74
Note: Codes are written in Java, So please change the syntax of the program according
to C# language.
1. Single Inheritance
Single Inheritance refers to a child and parent class relationship where a class extends the
another class.
class A
{
public int a=10, b=5;
}
class B : A
{
int a=30, b=5;
public void test()
{
Console.WriteLine("Value of a is: "+a);
Console.WriteLine("Value of a is: " + base.a);
}
}
75
//driver class
class Inherit
{
static void Main(string[] args)
{
B obj = new B();
obj.test();
Console.ReadLine();
}
}
2. Multilevel Inheritance
Multilevel inheritance refers to a child and parent class relationship where a class extends
the child class. For example, class C extends class B and class B extends class A.
class A5
{
public int a, b, c;
class A6 : A5
{
public void Add()
{
base.c = base.a + base.b;
Console.WriteLine("Sum="+base.c);
}
}
class A7 : A6
{
public void Sub()
{
base.c = base.a - base.b;
Console.WriteLine("Difference=" + base.c);
}
76
}
class Level
{
static void Main()
{
A7 obj = new A7();
obj.ReadData(20,5);
obj.Display();
obj.Add();
obj.Sub();
Console.ReadLine();
}
}
3. Hierarchical Inheritance
Hierarchical inheritance refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same class
A.
class Polygon
{
public int dim1,dim2;
public void ReadDimension(int dim1, int dim2)
{
this.dim1 = dim1;
this.dim2 = dim2;
}
}
77
}
}
//driver class
class Hier
{
static void Main()
{
Traingle tri = new Traingle();
//tri.ReadDimension(10,5);
tri.AreaTri();
Console.ReadLine();
}
}
4. Multiple Inheritance
When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance.
C# doesn’t allow multiple inheritance. We can use interfaces instead of classes to achieve
the same purpose.
interface IA
{
// doesn't contain fields
int CalculateArea();
int CalculatePerimeter();
}
class CA
{
public int l, b;
public void ReadData(int l,int b)
{
this.l = l;
this.b = b;
}
}
class BB : CA, IA
{
public int CalculateArea()
{
ReadData(10,5);
int area=l*b;
78
return area;
}
//driver class
class Inter
{
static void Main(string[] args)
{
BB obj = new BB();
//int area=obj.CalculateArea();
//int peri=obj.CalculatePerimeter();
Console.ReadKey();
}
}
Interface in C#
An interface looks like a class, but has no implementation. The only thing it contains are
declarations of events, indexers, methods and/or properties. The reason interfaces only
provide declarations is because they are inherited by structs and classes, that must provide
an implementation for each interface member declared.
Like a class, an interface can have methods and properties, but the methods declared in
interface are by default abstract (only method signature, no body).
❖ Interfaces specify what a class must do and not how. It is the blueprint of the class.
❖ An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move (). So it specifies a
set of methods that the class has to implement.
❖ If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then class must be declared abstract.
79
interface IA
{
// doesn't contain fields
void GetData(int l,int b);
int CalculateArea();
int CalculatePerimeter();
}
class BB : IA
{
int l, b;
public void GetData(int l, int b)
{
this.l = l;
this.b = b;
}
public int CalculateArea()
{
int area=l*b;
return area;
}
//driver class
class Inter
{
static void Main(string[] args)
{
BB obj = new BB();
obj.GetData(10,5);
Console.WriteLine("Area of Rectangle=" + obj.CalculateArea());
Console.WriteLine("Perimeter of Rectangle=" +
obj.CalculatePerimeter());
Console.ReadKey();
}
}
Output:
Area of Rectangle=50
Perimeter of Rectangle=30
80
Abstract Classes
A class declared as abstract can never be instantiated. Instead, only its concrete sub‐
classes can be instantiated.
If a class is defined as abstract then we can't create an instance of that class. By the creation
of the derived class object where an abstract class is inherit from, we can call the method
of the abstract class.
For example,
Abstract Members
An Abstract method is a method without a body. The implementation of an abstract
method is done by a derived class. When the derived class inherits the abstract method
from the abstract class, it must override the abstract method. This requirement is enforced
at compile time and is also called dynamic polymorphism.
Abstract members are used to achieve total abstraction.
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
} }
81
public class TestAbstract
{
public static void Main()
{
Rectangle s = new Rectangle();
s.draw();
}
}
Output:
drawing ractangle...
Another Example
In the above program, one method i.e. mul can perform various functions depending on
the value passed as parameters by creating an object of various classes which inherit other
classes. Hence we can acheive dynamic polymorphism with the help of an abstract method.
82
Polymorphism
Polymorphism in C# is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means
many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
Method Overloading
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor overloading
in Java, that allows a class to have more than one constructor having different argument
lists. In order to overload a method, the argument lists of the methods must differ in either
of these:
a) Number of parameters.
add(int, int)
add(int, int, int)
b) Data type of parameters.
add(int, int)
add(int, float)
c) Sequence of Data type of parameters.
add(int, float)
add(float, int)
83
Example of Method Overloading
Method Overriding
Method overriding in C# allows programmers to create base classes that allows its
inherited classes to override same name methods when implementing in their class for
different purpose. This method is also used to enforce some must implement features in
derived classes.
Important points:
• Method overriding is only possible in derived classes, not within the same class
where the method is declared.
• Base class must use the virtual or abstract keywords to declare a method. Then only
can a method be overridden
84
class Test
{
static void Main()
{
Amount obj = new Amount();
int balance = obj.balance();
Console.WriteLine("Balance is: "+balance);
Console.ReadKey();
}
}
Output:
Balance is 500
Virtual Method
A virtual method is a method that can be redefined in derived classes. A virtual method has
an implementation in a base class as well as derived the class. It is used when a method's
basic functionality is the same but sometimes more functionality is needed in the derived
class. A virtual method is created in the base class that can be overriden in the derived
class. We create a virtual method in the base class using the virtual keyword and that
method is overriden in the derived class using the override keyword.
class Vir
{
public virtual void message()
{
Console.WriteLine("This is test");
}
}
class Program
{
static void Main(string[] args)
{
Vir obj = new Vir();
obj.message();
Console.ReadKey();
}
}
85
Behaviour of virtual method with inheritance – used for overriding
class Vir
{
public virtual void message()
{
Console.WriteLine("This is test");
}
}
class Program
{
static void Main(string[] args)
{
Vir1 obj = new Vir1();
obj.message();
Console.ReadKey();
}
}
Output:
This is test1
86
The as operator
The as operator performs a downcast that evaluates to null (rather than throwing an
exception) if the downcast fails:
Asset a = new Asset();
Stock s = a as Stock; // s is null; no exception thrown
The is operator
The is operator tests whether a reference conversion would succeed; in other words,
whether an object derives from a specified class (or implements an inter‐ face). It is often
used to test before downcasting.
if (a is Stock)
Console.WriteLine (((Stock)a).SharesOwned);
Operator Overloading
The concept of overloading a function can also be applied to operators. Operator
overloading gives the ability to use the same operator to do various operations. It provides
additional capabilities to C# operators when they are applied to user-defined data types. It
enables to make user-defined implementations of various operations where one or both
of the operands are of a user-defined class.
Only the predefined set of C# operators can be overloaded. To make operations on a user-
defined data type is not as simple as the operations on a built-in data type. To use operators
with user-defined data types, they need to be overloaded according to a programmer’s
requirement. An operator can be overloaded by defining a function to it. The function of
the operator is declared by using the operator keyword.
Syntax:
access specifier className operator Operator_symbol (parameters)
{
// Code
}
87
The following table describes the overloading ability of the various operators available
in C# :
OPERATORS DESCRIPTION
+, -, !, ~, ++, – – unary operators take one operand and can be overloaded.
+, -, *, /, % Binary operators take two operands and can be overloaded.
==, !=, = Comparison operators can be overloaded.
&&, || Conditional logical operators cannot be overloaded directly
+=, -+, *=, /=, %=, = Assignment operators cannot be overloaded.
88
Overloading Binary Operators
An overloaded binary operator must take two arguments; at least one of them must be of
the type class or struct, in which the operation is defined.
89
Sealed Methods and Properties
You can also use the sealed modifier on a method or a property that overrides a virtual
method or property in a base class.
This enables you to allow classes to derive from your class and prevent other developers
that are using your classes from overriding specific virtual methods and properties.
90
The base Keyword
We can use the base keyword to access the fields of the base class within derived class. It
is useful if base and derived classes have the same fields.
If derived class doesn't define same field, there is no need to use base keyword. Base
class field can be directly accessed by the derived class.
using System;
public class Animal{
public string color = "white";
}
public class Dog: Animal
{
string color = "black";
public void showColor()
{
Console.WriteLine(base.color); //displays white
Console.WriteLine(color); //displays black
}
}
public class TestBase
{
public static void Main()
{
Dog d = new Dog();
d.showColor();
}
}
91
Console.WriteLine("Value of x={0} and y={1}", x, y);
}
}
class BaseEx
{
static void Main(){
new Derived(10,5);
Console.ReadKey();
}
}
Output:
Value of a=10 and b=5
Value of x=10 and y=5
Output:
I am inside base class
I am inside derived class
92
The object Type
object (System.Object) is the ultimate base class for all types. Any type can be upcast to
object.
To illustrate how this is useful, consider a general-purpose stack. A stack is a data structure
based on the principle of LIFO—“Last-In First-Out.” A stack has two operations: push an
object on the stack, and pop an object off the stack.
Here is a simple implementation that can hold up to 10 objects:
Unboxing reverses the operation, by casting the object back to the original value type:
int y = (int)obj; // Unbox the int
Unboxing requires an explicit cast. The runtime checks that the stated value type matches
the actual object type, and throws an InvalidCastException if the check fails.
For instance, the following throws an exception, because long does not exactly match int:
93
The GetType Method and typeof Operator
All types in C# are represented at runtime with an instance of System.Type. There are two
basic ways to get a System.Type object:
• Call GetType on the instance.
• Use the typeof operator on a type name.
System.Type has properties for such things as the type’s name, assembly, base type, and
so on. For example:
Structs
A struct is similar to a class, with the following key differences:
• A struct is a value type, whereas a class is a reference type.
• A struct does not support inheritance
.
A struct can have all the members a class can, except the following:
• A parameter less constructor
• Field initializers
• A finalizer
• Virtual or protected members
94
Here is an example of declaring and calling struct:
Access Modifiers
Access modifiers in C# are used to specify the scope of accessibility of a member of a class
or type of the class itself. For example, a public class is accessible to everyone without any
restrictions, while an internal class may be accessible to the assembly only.
Access modifiers are an integral part of object-oriented programming. Access modifiers are
used to implement encapsulation of OOP. Access modifiers allow you to define who does
or who doesn't have access to certain features.
95
Modifier Description
public There are no restrictions on accessing public members.
private Access is limited to within the class definition. This is the default access
modifier type if none is formally specified
protected Access is limited to within the class definition and any class that inherits
from the class
internal Access is limited exclusively to classes defined within the current project
assembly
protected Access is limited to the current assembly and types derived from the
internal containing class. All members in current project and all members in
derived class can access the variables.
private Access is limited to the containing class or types derived from the
protected containing class within the current assembly.
96
Enums in C#
Enum in C# language is a value type with a set of related named constants often referred
to as an enumerator list. The enum keyword is used to declare an enumeration. It is a
primitive data type, which is user-defined. Enums type can be an integer (float, int, byte,
double etc.) but if you use beside int, it has to be cast.
Enum is used to create numeric constants in .NET framework. All member of the enum are
of enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration elements is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased by
1.
Output
The value of jan in month enum is 0
The value of feb in month enum is 1
The value of mar in month enum is 2
The value of apr in month enum is 3
The value of may in month enum is 4
97
Generics
Generics in C# and .NET procedure many of the benefits of strongly-typed collections as
well as provide a higher quality of and a performance boost for code.
Generics are very similar to C++ templates but having a slight difference in such a way that
the source code of C++ templates is required when a template is instantiated with a specific
type and .NET Generics are not limited to classes only. In fact, they can also be
implemented with Interfaces, Delegates and Methods.
The detailed specification for each collection is found under the System.Collection.Generic
namespace.
Generic Classes
The Generic class can be defined by putting the <T> sign after the class name. It isn't
mandatory to put the "T" word in the Generic type definition. You can use any word in the
TestClass<> class declaration.
public class TestClass<T> { }
using System.Collections.Generic;
class Test<T>
{
T[] t=new T[5];
int count = 0;
public void addItem(T item)
{
if (count < 5)
{
t[count] = item;
count++;
}
else
{
Console.WriteLine("Overflow exists");
}
}
98
public void displayItem()
{
for (int i = 0; i < count; i++)
{
Console.WriteLine("Item at index {0} is {1}",i,t[i]);
}
}
}
class GenericEx
{
static void Main()
{
Test<int> obj = new Test<int>();
obj.addItem(10);
obj.addItem(20);
obj.addItem(30);
obj.addItem(40);
obj.addItem(50);
//obj.addItem(60); //overflow exists
obj.displayItem();
Console.ReadKey();
}
}
Output
Item at index 0 is 10
Item at index 1 is 20
Item at index 2 is 30
Item at index 3 is 40
Item at index 4 is 50
Generic Methods
The objective of this example is to build a swap method that can operate on any possible
data type (value-based or reference-based) using a single type parameter. Due to the
nature of swapping algorithms, the incoming parameters will be sent by reference via ref
keyword.
99
using System.Collections.Generic;
Output
Before swap: 40, 60
After swap: 60, 40
Dictionary
Dictionaries are also known as maps or hash tables. It represents a data structure that
allows you to access an element based on a key. One of the significant features of a
dictionary is faster lookup; you can add or remove items without the performance
overhead.
.Net offers several dictionary classes, for instance Dictionary<TKey, TValue>. The type
parameters TKey and TValue represent the types of the keys and the values it can store,
respectively.
using System.Collections.Generic;
public class Program
{
static void Main(string[] args)
{
//define Dictionary collection
Dictionary<int, string> dObj = new Dictionary<int,
string>(5);
//add elements to Dictionary
dObj.Add(1, 1, "Tom");
dObj.Add(2, "John");
dObj.Add(3, "Maria");
100
dObj.Add(4, "Max");
dObj.Add(5, "Ram");
//print data
for (int i = 1; i <= dObj.Count; i++)
{
Console.WriteLine(dObj[i]);
}
Console.ReadKey();
}
}
Queues
Queues are a special type of container that ensures the items are being accessed in a FIFO
(first in, first out) manner. Queue collections are most appropriate for implementing
messaging components. We can define a Queue collection object using the following
syntax:
Queue qObj = new Queue();
The Queue collection property, methods and other specification definitions are found
under the Sysyem.Collection namespace. The following table defines the key members;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
Queue < string > queue1 = new Queue < string > ();
queue1.Enqueue("MCA");
queue1.Enqueue("MBA");
queue1.Enqueue("BCA");
queue1.Enqueue("BBA");
101
Console.WriteLine("After removal the elements in the
queue are:");
foreach(string s in queue1) {
Console.WriteLine(s);
}
}
}
Stacks
A Stack collection is an abstraction of LIFO (last in, first out). We can define a Stack
collection object using the following syntax:
Stack qObj = new Stack();
The following table illustrates the key members of a stack;
class Program {
static void Main(string[] args) {
Stack < string > stack1 = newStack < string > ();
stack1.Push("************");
stack1.Push("MCA");
stack1.Push("MBA");
stack1.Push("BCA");
stack1.Push("BBA");
stack1.Push("***********");
stack1.Push("**Courses**");
stack1.Push("***********");
Console.WriteLine("The elements in the stack1 are
as:");
foreach(string s in stack1) {
Console.WriteLine(s);
}
102
foreach(string s in stack1) {
Console.WriteLine(s);
}
}
}
List
List<T> class in C# represents a strongly typed list of objects. List<T> provides functionality
to create a list of objects, find list items, sort list, search list, and manipulate list items. In
List<T>, T is the type of objects.
Adding Elements
// Dynamic ArrayList with no size limit
List<int> numberList = new List<int>();
numberList.Add(32);
numberList.Add(21);
numberList.Add(45);
numberList.Add(11);
numberList.Add(89);
// List of string
List<string> authors = new List<string>(5);
authors.Add("Mahesh Chand");
authors.Add("Chris Love");
authors.Add("Allen O'neill");
authors.Add("Naveen Sharma");
authors.Add("Monica Rathbun");
authors.Add("David McCarter");
// Collection of string
string[] animals = { "Cow", "Camel", "Elephant" };
// Create a List and add a collection
List<string> animalsList = new List<string>();
animalsList.AddRange(animals);
foreach (string a in animalsList)
Console.WriteLine(a);
Remove Elements
// Remove an item
authors.Remove("New Author1");
Sorting
authors.Sort();
103
Other Methods
authors.Insert(1,"Shaijal"); //insert item at index 1
authors.Count; //returns total items
Array List
C# ArrayList is a non-generic collection. The ArrayList class represents an array list and it
can contain elements of any data types. The ArrayList class is defined in the
System.Collections namespace. An ArrayList is dynamic array and grows automatically
when new items are added to the collection.
Insertion
personList.Add("Sandeep");
Removal
// Remove an item
personList.Remove("New Author1");
Sorting
personList.Sort();
Other Methods
personList.Insert(1,"Shaijal"); //insert item at index 1
personList.Count; //returns total items
104
Unit - 4 Advanced C# [14 Hrs]
Delegates; Events; Lambda Expressions; Exception Handling; Introduction to LINQ;
Working with Databases; Web Applications using ASP.NET
Delegates
A delegate is an object that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically, it
defines the method’s return type and its parameter types.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the System.Delegate class. It provides a way which
tells which method is to be called when an event is triggered.
For example, if you click an Button on a form (Windows Form application), the program
would call a specific method.
In simple words, it is a type that represents references to methods with a particular
parameter list and return type and then calls the method in a program for execution when
it is needed.
Declaring Delegates
Delegate type can be declared using the delegate keyword. Once a delegate is declared,
delegate instance will refer and call those methods whose return type and parameter-list
matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
modifier: It is the required modifier which defines the access of delegate and it is optional
to use.
delegate: It is the keyword which is used to define the delegate.
return_type: It is the type of value returned by the methods which the delegate will be going
to call. It can be void. A method must have the same return type as the delegate.
delegate_name: It is the user-defined name or identifier for the delegate.
parameter_list: This contains the parameters which are required by the method when
called through the delegate.
Note: A delegate will call only a method which agrees with its signature and return type. A
method can be a static method associated with a class or can be an instance method
associated with an object, it doesn’t matter.
105
[delegate_name] [instance_name] = new
[delegate_name](calling_method_name);
Transformer is compatible with any method with an int return type and a single int
parameter, such as this:
static int Square (int x) { return x * x; }
or
static int Square (int x) => x * x;
Output:
Result is : 25
106
Example 2
using System;
class TestDelegate {
static int num = 10;
Output:
Value of Num: 35
Value of Num: 175
Example 3
class Test
{
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
// method "sum"
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}
107
// method "subtract"
public void subtract(int a, int b)
{
Console.WriteLine("(100 - 60) = {0}", a - b);
}
// Main Method
public static void Main(String[] args)
{
addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);
Output:
(100 + 40) = 140
(100 - 60) = 40
Multicast Delegates
All delegate instances have multicast capability. This means that a delegate instance can
reference not just a single target method, but also a list of target methods.
The + and += operators combine delegate instances. For example:
SomeDelegate d = SomeMethod1;
d += SomeMethod2;
The - and -= operators remove the right delegate operand from the left delegate operand.
For example:
d -= SomeMethod1;
Invoking d will now cause only SomeMethod2 to be invoked.
108
Example of multicasting delegates
using System;
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
Output
Value of Num: 75
109
Delegates Mapping with Instance and Static Method
Created ClassA contains instance & static method,
Output
Instance Method
Static Method
So using delegate, we can associate instance and static method under same delegate
instance.
110
Delegates Vs Interfaces in C#
Delegate Compatibility
Type compatibility
Delegate types are all incompatible with one another, even if their signatures are the same:
111
Delegate instances are considered equal if they have the same method targets:
Parameter compatibility
When you call a method, you can supply arguments that have more specific types than the
parameters of that method. This is ordinary polymorphic behaviour. For exactly the same
reason, a delegate can have more specific parameter types than its method target. This is
called contravariance.
In this case, the String Action is invoked with an argument of type string. When the
argument is then relayed to the target method, the argument gets implicitly up cast to an
object.
112
Generic Delegate Types
A delegate type may contain generic type parameters. For example:
public delegate T Transformer (T arg);
With this definition, we can write a generalized Transform utility method that works on
any type:
Since both the delegates are generic, you will need to specify the underlying types of each
parameter as well while pointing it to a function. For for example
Action<type,type,type……>
Action<>
• This Action<> generic delegate; points to a method that takes up to 16 Parameters
and returns void.
Func<>
• The generic Func<> delegate is used when we want to point to a method that
returns a value.
• This delegate can point to a method that takes up to 16 Parameters and returns a
value.
113
• Always remember that the final parameter of Func<> is always the return value of
the method. (For example, Func< int, int, string>, this version of the Func<>
delegate will take 2 int parameters and returns a string value.)
class MethodCollections
{
//Methods that takes parameters but returns nothing:
}
public static int ShowNumber()
{
Random r = new Random();
return r.Next();
}
}
114
class Program
{
static void Main(string[] args)
{
Action printText = new Action(MethodCollections.PrintText);
Action<string> print = new Action<string>(MethodCollections.Pr
int);
Action<int, int> printNumber = new Action<int, int>(MethodColl
ections.PrintNumbers);
Console.ReadLine();
}
}
115
Events
Events are user actions such as key press, clicks, mouse movements, etc., or some
occurrence such as system generated notifications. Applications need to respond to events
when they occur. For example, interrupts. Events are used for inter-process
communication.
The class that sends or raises an event is called a Publisher and class that receives or
handle the event is called "Subscriber".
Declaring Events
To declare an event inside a class, first of all, you must declare a delegate type for the even
as:
public delegate string MyDelegate(string str);
The preceding code defines a delegate named MyDelegate and an event named delg,
which invokes the delegate when it is raised.
To declare an event inside a class, first a Delegate type for the Event must be declared
like below:
public delegate void MyEventHandler(object sender, EventArgs e);
Defining an event is a two-step process.
• First, you need to define a delegate type that will hold the list of methods to be
called when the event is fired.
• Next, you declare an event using the event keyword.
To illustrate the event, we are creating a console application. In this iteration, we will define
an event to add that is associated to a single delegate DelEventHandler.
using System;
public delegate void DelEventHandler();
class Program
{
public static event DelEventHandler add;
116
static void USA()
{
Console.WriteLine("USA");
}
Console.ReadLine();
}
using System;
using System.Drawing;
using System.Windows.Forms;
//custom delegate
public delegate void DelEventHandler();
public Program()
{
// design a button over form
Button btn = new Button();
btn.Parent = this;
btn.Text = "Hit Me";
btn.Location = new Point(100,100);
117
// the button click event
btn.Click += new EventHandler(onClcik);
add += new DelEventHandler(Initiate);
Console.ReadLine();
}
}
118
Anonymous Method in C#
An anonymous method is a method which doesn’t contain any name which is introduced
in C# 2.0. It is useful when the user wants to create an inline method and also wants to
pass parameter in the anonymous method like other methods.
An Anonymous method is defined using the delegate keyword and the user can assign
this method to a variable of the delegate type.
delegate(parameter_list){
// Code..
};
Example:
using System;
class GFG {
// Main method
static public void Main()
{
Output:
My favorite pet is: Dog
119
Lambda Expressions
Lambda expressions in C# are used like anonymous functions, with the difference that in
Lambda expressions you don’t need to specify the type of the value that you input thus
making it more flexible to use.
The ‘=>’ is the lambda operator which is used in all lambda expressions. The Lambda
expression is divided into two parts, the left side is the input and the right is the expression.
class LambdaTest
{
static int test1() => 5;
static int test2(int x) => x + 10;
Output:
Result is: 15
120
Exception Handling
A try statement specifies a code block subject to error-handling or clean-up code. The try
block must be followed by a catch block, a finally block, or both. The catch block executes
when an error occurs in the try block. The finally block executes after execution leaves the
try block (or if present, the catch block), to per‐ form clean-up code, whether or not an
error occurred.
A catch block has access to an Exception object that contains information about the error.
You use a catch block to either compensate for the error or re throw the exception. You re
throw an exception if you merely want to log the problem, or if you want to re throw a
new, higher-level exception type.
A finally block adds determinism to your program: the CLR endeavours to always execute
it. It’s useful for clean-up tasks such as closing network connections.
121
The catch Clause
A catch clause specifies what type of exception to catch. This must either be
System.Exception or a subclass of System.Exception.
You can handle multiple exception types with multiple catch clauses:
122
The finally Block
A finally block always executes—whether or not an exception is thrown and whether or
not the try block runs to completion. finally blocks are typically used for clean-up code.
A finally block executes either:
• After a catch block finishes
• After control leaves the try block because of a jump statement (e.g., return or
goto)
• After the try block ends
Throwing Exceptions
Exceptions can be thrown either by the runtime or in user code. In this example, Display
throws a System.ArgumentNullException:
Re-throwing an exception
You can capture and re-throw an exception as follows:
123
Common Exception Types
System.ArgumentException
Thrown when a function is called with a bogus argument. This generally indi‐ cates a
program bug.
System.ArgumentNullException
Subclass of ArgumentException that’s thrown when a function argument is (unexpectedly)
null.
System.ArgumentOutOfRangeException
Subclass of ArgumentException that’s thrown when a (usually numeric) argu‐ ment is too
big or too small. For example, this is thrown when passing a nega‐ tive number into a
function that accepts only positive values.
System.InvalidOperationException
Thrown when the state of an object is unsuitable for a method to successfully execute,
regardless of any particular argument values. Examples include read‐ ing an unopened file
or getting the next element from an enumerator where the underlying list has been
modified partway through the iteration.
System.NotSupportedException
Thrown to indicate that a particular functionality is not supported. A good example is
calling the Add method on a collection for which IsReadOnly returns true.
System.NotImplementedException
Thrown to indicate that a function has not yet been implemented.
System.ObjectDisposedException
Thrown when the object upon which the function is called has been disposed.
124
Introduction to LINQ
LINQ (Language Integrated Query) is uniform query syntax in C# to retrieve data from
different sources and formats. It is integrated in C#, thereby eliminating the mismatch
between programming languages and databases, as well as providing a single querying
interface for different types of data sources.
For example, SQL is a Structured Query Language used to save and retrieve data from a
database. In the same way, LINQ is a structured query syntax built in C# to retrieve data
from different types of data sources such as collections, ADO.Net DataSet, XML Docs, web
service and MS SQL Server and other databases.
LINQ queries return results as objects. It enables you to uses object-oriented approach on
the result set and not to worry about transforming different formats of results into objects.
The following example demonstrates a simple LINQ query that gets all strings from an
array which contains 'a'.
125
Example: LINQ Query to List
// string collection
List<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};
LINQ Method
The following is a sample LINQ method syntax query that returns a collection of strings
which contains a word "Tutorials". We use lambda expression for this purpose.
126
foreach (var num in evenNumbers)
{
Console.Write("{0} ", num);
}
Console.WriteLine();
Console.Read();
}
}
Output:
2 4 6
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
class Dog
{
public string Name { get; set; }
public int Age { get; set; }
}
class demo{
static void Main()
{
List<Dog> dogs = new List<Dog>() {
new Dog { Name = "Rex", Age = 4 },
new Dog { Name = "Sean", Age = 0 },
new Dog { Name = "Stacy", Age = 3 }
};
var names = dogs.Select(x => x.Name);
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.Read();
}
}
Output:
Rex
Sean
Stacy
127
Sorting using a lambda expression
var sortedDogs = dogs.OrderByDescending(x => x.Age);
foreach (var dog in sortedDogs)
{
Console.WriteLine(“Dog {0} is {1} years old.", dog.Name, dog.Age
);
}
Output:
Dog Rex is 4 years old.
Dog Stacy is 3 years old.
Dog Sean is 0 years old.
LINQ Operators
128
Some examples of LINQ Query
//Multiple Condition
var result = names.Where(s=>s.Contains("Ram") ||
s.Contains("Gita"));
foreach (string val in result)
{
Console.WriteLine(val);
}
Console.ReadLine();
}
}
}
Output:
Ram
Gita
class LinqTest
{
static void Main(string[] args)
129
{
List<Student> mylist = new List<Student>(){
new Student(1,"Ram","Btm"),
new Student(2, "Hari", "Ktm"),
new Student(3,"Shyam","Btm"),
new Student(4, "Gita", "Ktm")
};
Console.WriteLine(res.sid+"\t"+res.name+"\t"+res.address);
}
Console.ReadLine();
}
}
Output:
Sid Name Address
1 Ram Btm
//using union
var result = names.Union(address);
foreach (var res in result)
{
Console.WriteLine(res);
}
Console.ReadLine();
} }
130
Using aggregate functions – Example 1
class LinqTest
{
static void Main(string[] args)
{
List<int> marks = new List<int>() { 10,30,50,20,5};
int max = marks.Max();
int min = marks.Min();
int sum = marks.Sum();
int total = marks.Count();
Console.WriteLine("Maximum marks="+max);
Console.WriteLine("Minimum marks=" + min);
Console.WriteLine("Sum of marks=" + sum);
Console.WriteLine("Total Count=" + total);
Console.ReadLine();
}
}
class Student
{
public int sid { get; set; }
public string name { get; set; }
public string address { get; set; }
class LinqTest
{
static void Main(string[] args)
{
List<Student> mylist = new List<Student>(){
new Student(1,"Ram","Btm"),
new Student(2, "Hari", "Ktm"),
new Student(3,"Shyam","Btm"),
new Student(4, "Gita", "Ktm")
};
131
Console.WriteLine("Total Students="+count);
Console.ReadLine();
}
}
Output
Max Id=4
Total Students=4
Using Order By
class Student
{
public int sid { get; set; }
public string name { get; set; }
public string address { get; set; }
class LinqTest
{
static void Main(string[] args)
{
List<Student> mylist = new List<Student>(){
new Student(1,"Ram","Btm"),
new Student(2, "Hari", "Ktm"),
new Student(3,"Shyam","Btm"),
new Student(4, "Gita", "Ktm")
};
Console.WriteLine("Name\tAddress");
foreach (var res in result)
{
Console.WriteLine(res.name + "\t" + res.address);
}
132
Console.ReadLine();
}
}
Output:
Name Address
Gita Ktm
Hari Ktm
Using Group By
class Student
{
public int sid { get; set; }
public string name { get; set; }
public string address { get; set; }
class LinqTest
{
static void Main(string[] args)
{
List<Student> mylist = new List<Student>(){
new Student(1,"Ram","Btm"),
new Student(2, "Hari", "Ktm"),
new Student(3,"Shyam","Btm"),
new Student(4, "Gita", "Ktm")
};
Console.WriteLine(res.sid+"\t"+res.name+"\t"
+ res.address);
}
133
}
Console.ReadLine();
}
}
Output:
Group Key: Btm
Sid Name Address
1 Ram Btm
3 Shyam Btm
Group Key: Ktm
Sid Name Address
2 Hari Ktm
4 Gita Ktm
134
Working with Databases
ADO : ActiveX Data Objects and ADO.Net are two different ways to access database in
Microsoft.
ADO ADO.Net
ADO is base on COM : Component Object ADO.Net is based on CLR : Common
Modelling based. Language Runtime based.
ADO stores data in binary format. ADO.Net stores data in XML format i.e.
parsing of data.
ADO can’t be integrated with XML because ADO.Net can be integrated with XML as
ADO have limited access of XML. having robust support of XML.
ADO is connection oriented means it requires ADO.Net is disconnected, does not need
continuous active connection. continuous connection.
ADO gives rows as single table view, it scans ADO.Net gives rows as collections so you can
sequentially the rows access any record and also can go through a
using MoveNext method. table via loop.
In ADO, You can create only Client side cursor. In ADO.Net, You can create both Client &
Server side cursor.
Using a single connection instance, ADO can Using a single connection instance, ADO.Net
not handle multiple transactions. can handle multiple transactions.
135
Working with Connection, Command:
Working with Connection:
Process of creating connection:
For SQL Server
Note: Sql Server must be installed
String conn_str;
SqlConnection connection;
conn_str = "Data Source=DESKTOP-EG4ORHN\SQLEXPRESS; Initial Catalog=billing;
User ID=sa;Password=24518300";
connection = New SqlConnection(conn_str);
(Here, DESKTOP-EG4ORHN\SQLEXPRESS refers to a data source and billing refers to
database name)
For MS-Access
Note: Access Database Engine must be installed
OleDbConnection conn;
OleDbCommand command;
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\\Users\\Raazu\\Documents\\Visual Studio
2012\\Projects\\DatabaseTest\\testdb.accdb";
conn = new OleDbConnection(constr);
conn.Open();
136
DataReader, DataAdaper, Dataset and Datatable :
DataReader is used to read the data from database and it is a read and forward only
connection oriented architecture during fetch the data from database. DataReader will
fetch the data very fast when compared with dataset. Generally we will use ExecuteReader
object to bind data to dataReader.
//Example
SqlDataReader sdr = cmd.ExecuteReader();
DataReader
- Holds the connection open until you are finished (don't forget to close it!).
- Can typically only be iterated over once
- Is not as useful for updating back to the database
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object
is used to read the data from database and bind that data to dataset. Dataadapter is a
disconnected oriented architecture.
//Example
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataAdapter
- Lets you close the connection as soon it's done loading data, and may even close it
for you automatically
- All of the results are available in memory
- You can iterate over it as many times as you need, or even look up a specific record
by index
- Has some built-in faculties for updating back to the database.
DataTable represents a single table in the database. It has rows and columns. There is no
much difference between dataset and datatable, dataset is simply the collection of
datatables.
//Example
DataTable dt = new DataTable();
da.Fill(dt);
137
Difference between DataReader and DataAdapter:
1) A DataReader is an object returned from the ExecuteReader method of a DbCommand
object. It is a forward-only cursor over the rows in the each result set. Using a DataReader,
you can access each column of the result set, read all rows of the set, and advance to the
next result set if there are more than one.
A DataAdapter is an object that contains four DbCommand objects: one each for SELECT,
INSERT, DELETE and UPDATE commands. It mediates between these commands and a
DataSet though the Fill and Update methods.
2) DataReader is a faster way to retrieve the records from the DB. DataReader reads the
column. DataReader demands live connection but DataAdapter needs disconnected
approach.
3) Data reader is an object through which you can read a sequential stream of data. it's a
forward only data wherein you cannot go back to read previous data. data set and data
adapter object help us to work in disconnected mode. data set is an in cache memory
representation of tables. the data is filled from the data source to the data set thro' the
data adapter. once the table in the dataset is modified, the changes are broadcast to the
database back throw; the data adapter.
138
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count != 0)
{
Console.WriteLine("Sid\t Name\t Address");
for (int i = 0; i < dt.Rows.Count;i++)
{
string sid = dt.Rows[i]["sid"].ToString();
string name = dt.Rows[i]["name"].ToString();
string address = dt.Rows[i]["address"].ToString();
Console.WriteLine(sid+"\t"+name+"\t"+address);
}
}
}
139
break;
case 4:
sql = "SELECT * FROM tblStudent";
obj.SelectRecords(sql);
break;
default:
Console.WriteLine("Wrong Choice");
break;
}
goto x;
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Connection Failed !");
}
Console.ReadKey();
}
}
Connect C# to MySQL
• First make sure you have downloaded and installed the MySQL Connector/NET
from the MySQL official website.
• Add reference MySql.Data in your project.
using MySql.Data.MySqlClient;
string constr = "SERVER=localhost; DATABASE=dbtest; UID=root;
PASSWORD=;";
MySqlConnection conn = new MySqlConnection(constr);
140
void InsertUpdateDelete(string sql)
{
command = new MySqlCommand(sql, conn);
command.ExecuteNonQuery();
Console.WriteLine("Operation Performed Successfully !");
}
case 2:
Console.WriteLine("Enter id to be updated");
id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ënter Name of Student: ");
141
nm = Console.ReadLine();
Console.WriteLine("Ënter Address of Student: ");
add = Console.ReadLine();
sql = "UPDATE tblStudent SET name='"+nm+"',
address='"+add+"' WHERE sid="+id;
obj.InsertUpdateDelete(sql);
break;
case 3:
Console.WriteLine("Enter id to be deleted");
id = Convert.ToInt32(Console.ReadLine());
sql = "DELETE FROM tblStudent WHERE sid="+id;
obj.InsertUpdateDelete(sql);
break;
case 4:
sql = "SELECT * FROM tblStudent";
obj.SelectRecords(sql);
break;
default:
Console.WriteLine("Wrong Choice");
break;
}
goto x;
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Connection Failed !");
}
Console.ReadKey();
}
}
}
142
conn = new SqlConnection(constr);
conn.Open();
}
143
case 2:
Console.WriteLine("Enter id to be updated");
id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ënter Name of Student: ");
nm = Console.ReadLine();
Console.WriteLine("Ënter Address of Student: ");
add = Console.ReadLine();
sql = "UPDATE tblStudent SET name='"+nm+"',
address='"+add+"' WHERE sid="+id;
obj.InsertUpdateDelete(sql);
break;
case 3:
Console.WriteLine("Enter id to be deleted");
id = Convert.ToInt32(Console.ReadLine());
sql = "DELETE FROM tblStudent WHERE sid="+id;
obj.InsertUpdateDelete(sql);
break;
case 4:
sql = "SELECT * FROM tblStudent";
obj.SelectRecords(sql);
break;
default:
Console.WriteLine("Wrong Choice");
break;
}
goto x;
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Connection Failed !");
}
Console.ReadKey();
}
}
}
144
Writing Windows Form Applications
Introduction to Win Forms:
Windows Forms (WinForms) is a graphical (GUI) class library included as a part of Microsoft
.NET Framework, providing a platform to write rich client applications for desktop, laptop,
and tablet PCs.
A Windows Forms application is an event-driven application supported by Microsoft's .NET
Framework. Unlike a batch program, it spends most of its time simply waiting for the user
to do something, such as fill in a text box or click a button.
All visual elements in the Windows Forms class library derive from the Control class. This
provides a minimal functionality of a user interface element such as location, size, color,
font, text, as well as common events like click and drag/drop.
Basic Controls:
The following table lists some of the commonly used controls:
1 Forms
The container for all the controls that make up the user interface.
2 TextBox
3 Label
4 Button
5 ListBox
6 ComboBox
7 RadioButton
145
It enables the user to select a single option from a group of choices when paired
with other RadioButton controls.
8 CheckBox
9 PictureBox
10 ProgressBar
11 ScrollBar
12 DateTimePicker
It represents a Windows control that allows the user to select a date and a time
and to display the date and time with a specified format.
13 TreeView
14 ListView
It represents a Windows list view control, which displays a collection of items that
can be displayed using one of four different views.
146
Web Applications using ASP.NET
A Visual Studio Web application is built around ASP.NET. ASP.NET is a platform — including
design-time objects and controls and a run-time execution context — for developing and
running applications on a Web server.
ASP.NET Web applications run on a Web server configured with Microsoft Internet
Information Services (IIS). However, you do not need to work directly with IIS. You can
program IIS facilities using ASP.NET classes, and Visual Studio handles file management
tasks such as creating IIS applications when needed and providing ways for you to deploy
your Web applications to IIS.
147
Different Types of form controls in ASP.NET
Button Controls
ASP.NET provides three types of button control:
• Button : It displays text within a rectangular area.
• Link Button : It displays text that looks like a hyperlink.
• Image Button : It displays an image.
Label controls provide an easy way to display text which can be changed from one
execution of a page to the next. If you want to display text that does not change, you use
the literal text.
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
To create a group of radio buttons, you specify the same name for the GroupName
attribute of each radio button in the group. If more than one group is required in a single
form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially displayed,
set its Checked attribute to true. If the Checked attribute is set to true for multiple radio
buttons in a group, then only the last one is considered as true.
148
HyperLink Control
The HyperLink control is like the HTML <a> element.
<asp:HyperLink ID="HyperLink1" runat="server">
HyperLink
</asp:HyperLink>
Image Control
The image control is used for displaying images on the web page, or some alternative text,
if the image is not available.
<asp:Image ID="Image1" ImageUrl=”url” runat="server">
149
Example – 2 (Handling Events)
EventHandling.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="First Number">
</asp:Label>
<asp:TextBox ID="txtFirst" runat="server"></asp:TextBox>
<br/><br/>
<asp:Label ID="Label2" runat="server" Text="First Number">
</asp:Label>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<br/><br/>
<asp:Label ID="lblResult" runat="server" Text="Result:">
</asp:Label> <br/><br/>
<asp:Button ID="btnSubmit" runat="server" Text="Get Result"
onClick="btnSubmit_Click"/>
</div>
</form>
EventHandling.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
int first = Convert.ToInt32(txtFirst.Text);
int second = Convert.ToInt32(txtSecond.Text);
int res = first + second;
lblResult.Text = "Result: " + res;
}
150
Dropdown.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Program">
</asp:Label>
<asp:DropDownList ID="dropProgram" runat="server">
</asp:DropDownList>
<br/><br/>
<asp:Label ID="lblSelected" runat="server" Text="Selected:">
</asp:Label>
<br/><br/>
<asp:Button ID="btnSelect" runat="server" Text="Select"
OnClick="btnSelect_Click" />
</div>
</form>
Dropdown.cs
private void LoadData()
{
List<ListItem> mylist=new List<ListItem>();
mylist.Add(new ListItem("BCA","1"));
mylist.Add(new ListItem("BBA","2"));
mylist.Add(new ListItem("MCA","3"));
mylist.Add(new ListItem("MBA","4"));
dropProgram.Items.AddRange(mylist.ToArray());
}
example.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Gender"></asp:Label>
<asp:RadioButton ID="radioMale" Text="Male" GroupName="gender"
runat="server" />
<asp:RadioButton ID="radioFemale" Text="Female"
GroupName="gender" runat="server" />
<br/><br/>
<asp:Label ID="lblSelected" runat="server" Text="Selected
151
Radio:"> </asp:Label>
<br/><br/>
<asp:Button ID="btnSelect" runat="server" Text="Select"
OnClick="btnSelect_Click" />
</div>
</form>
example.cs
protected void btnSelect_Click(object sender, EventArgs e)
{
if (radioMale.Checked)
lblSelected.Text = "Male Selected";
else
lblSelected.Text = "Female Selected";
}
example.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Gender"></asp:Label>
<asp:CheckBox ID="chkMale" Text="Male" GroupName="gender"
runat="server" />
<asp:CheckBox ID="chkFemale" Text="Female"
GroupName="gender" runat="server" />
<br/><br/>
<asp:Label ID="lblSelected" runat="server" Text="Selected
Radio:"> </asp:Label>
<br/><br/>
<asp:Button ID="btnSelect" runat="server" Text="Select"
OnClick="btnSelect_Click" />
</div>
</form>
example.cs
protected void btnSelect_Click(object sender, EventArgs e)
{
if (chkMale.Checked)
lblSelected.Text = "Male Selected";
else
lblSelected.Text = "Female Selected";
}
152
Validation Controls in ASP.NET
An important aspect of creating ASP.NET Web pages for user input is to be able to check
that the information users enter is valid. ASP.NET provides a set of validation controls that
provide an easy-to-use but powerful way to check for errors and, if necessary, display
messages to the user.
There are six types of validation controls in ASP.NET
- RequiredFieldValidation Control
- CompareValidator Control
- RangeValidator Control
- RegularExpressionValidator Control
- CustomValidator Control
- ValidationSummary
153
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="validator1" runat="server"
ForeColor="Red" ErrorMessage="Name is Required !"
ControlToValidate="txtName"> </asp:RequiredFieldValidator>
<br/><br/>
154