Dot Net Complete Note - Unlocked
Dot Net Complete Note - Unlocked
Fifth
Technology SEMESTER
om
.c
tu
Mechi Multiple Campus
al
Bhadrapur, Jhapa
ep
an
bc
Notes Prepared By
Raju Poudel
Lecturer, MMC
Notes Prepared by: Raju Poudel [Lecturer, MMC] 1
Unit -1 Introduction to C# and .NET Framework [7 Hrs]
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#
om
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.
.c
As an object-oriented language, C# supports the concepts of encapsulation, inheritance,
tu
and polymorphism. All variables and methods, including the Main method, the
application's entry point, are encapsulated within class definitions.
al
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.
ep
3. It is component oriented.
4. It is easy to learn.
5. It is a structured language.
an
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) behaviour from its
internal (private) implementation details.
The distinctive features of C# from an object-oriented perspective are:
om
programming paradigm. Specifically:
the ability to write unnamed functions on the fly that “capture” variables (lambda
expressions), and the ability to perform list or reactive programming via query expressions.
ep
C# also makes it easy to define read-only fields and properties for writing immutable (read-
only) types.
Type Safety
an
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
bc
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
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.
om
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.
.c
Xamarin™ allows cross platform C# development for mobile applications, and Portable
tu
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.
al
C# and CLR
ep
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)
om
.c
tu
al
ep
an
bc
om
2. The runtime also enforces code robustness by implementing a strict type-and-code-
verification infrastructure called the common type system (CTS). The CTS ensures
that all managed code is self-describing.
3. The runtime also accelerates developer productivity. For example, programmers
can write applications in their development language of choice, yet take full
.c
advantage of the runtime, the class library, and components written in other
languages by other developers. Any compiler vendor who chooses to target the
tu
runtime can do so. Language compilers that target the .NET Framework make the
features of the .NET Framework available to existing code written in that language,
greatly easing the migration process for existing applications.
al
4. While the runtime is designed for the software of the future, it also supports
software of today and yesterday.
ep
The core libraries are sometimes collectively called the Base Class Library (BCL). The
entire framework is called the Framework Class Library (FCL).
om
.c
tu
al
ep
an
bc
om
Other Frameworks
.c
The Microsoft .NET Framework is the most expansive and mature framework, but runs only
tu
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:
al
For writing Windows 10 Store Apps and for targeting Windows 10 devices (mobile, XBox,
Surface Hub, Hololens). Your app runs in a sandbox to lessen the threat of malware,
prohibiting operations such as reading or writing arbitrary files.
an
macOS, and Linux. Unlike the .NET Frame‐ work, .NET Core can be packaged with the web
application and xcopy deployed (self-contained deployment).
Xamarin
For writing mobile apps that target iOS, Android, and Windows Mobile. The Xamarin
company was purchased by Microsoft in 2016.
om
.Net Standard 2.0
.Net Standard is a specification which dictates what the Base Class Libraries of different
.Net platforms should implement to unify the Base Class Libraries of different .Net
Platforms. Here, Platform means full .Net Framework, .Net Core, Xamarin, Silverlight, XBox
.c
etc. This also enables code sharing between applications that runs on these different
platforms. For example, a library or a component that is developed on top of a platform
tu
that implements specific .Net Standard version can be shared by all the applications that
runs on any of the platforms that implements same .Net Standard version.
al
Net Standard has solved all this in a different way, it provided an API specification which
an
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.
bc
om
The .NET Standard 2.0 includes the following new features:
1) A vastly expanded set of APIs
2) Support for .NET Framework libraries
3) Support for Visual Basic
4) Tooling support for .NET Standard libraries
if you write a library that targets .NET Standard 1.6, you will support not only recent
versions of the four major frameworks, but also .NET Core 1.0. And if you target .NET
Standard 1.3, you support everything we’ve already mentioned plus .NET Framework 4.6.0
ep
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.
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).
om
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).
.c
The System.Text.RegularExpressions namespace contains types that perform advanced
tu
pattern-based search-and-replace operations.
Collections
al
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
ep
standard interfaces that unify their common characteristics. All collection types are defined
in the following namespaces:
an
bc
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:
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-
om
specific features are not part of .NET Standard, and are avail‐ able only in the .NET
Framework.
.c
Since C# 5.0, this has become easier through asynchronous functions and high-level
constructs such as tasks and task combinators. Types for working with threads and
tu
asynchronous operations are in the System.Threading and System.Threading.Tasks
namespaces.
al
typically used to read and write directly to files and network connections, and can be
chained or wrapped in decorator streams to add compression or encryption functionality.
The .NET Stream and I/O types are defined in and under the System.IO namespace, and
an
the WinRT types for file I/O are in and under Windows.Storage.
Networking
bc
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,
om
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
.c
Code access, role, and identity security, and the transparency model introduced in CLR 4.0.
tu
Cryptography can be done in the Framework, covering encryption, hashing, and data
protection. The types for this are defined in:
System.Security
al
System.Security.Permissions
System.Security.Policy
ep
System.Security.Cryptography
Advanced Threading
an
om
Following are the different applied technologies:
.c
tu
User-Interface APIs
User-interface–based applications can be divided into two categories: thin client, which
al
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
ep
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.
an
Finally, there’s a hybrid technology called Silverlight, which has been largely abandoned
since the rise of HTML5.
bc
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.
om
Its primary measurement unit is not pixel-based, so applications display correctly
at any DPI (dots per inch) setting.
It has extensive and flexible layout support, which means you can localize an
application without danger of elements overlapping.
Rendering uses DirectX and is fast, taking good advantage of graphics hard‐ ware
acceleration.
It offers reliable data binding. .c
tu
User interfaces can be described declaratively in XAML files that can be maintained
independently of the “code-behind” files—this helps to separate appearance from
al
functionality.
ep
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
an
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).
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
om
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
.c
The provider model defines common classes and interfaces for low-level access to
tu
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
al
other databases.
DataSet model
ep
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.
bc
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.
om
COM+ and MSMQ (.NET Framework only)
The Framework allows you to interoperate with COM+ for services such as distributed
transactions, via types in the System.EnterpriseServices namespace.
It also supports MSMQ (Microsoft Message Queuing) for asynchronous, one-way
messaging through types in System.Messaging.
is flexible and configurable enough to make both of its predecessors— Remoting and
(.ASMX) Web Services—mostly redundant.
ep
WCF, Remoting, and Web Services are all alike in that they implement the following basic
model in allowing a client and server application to communicate:
On the server, you indicate what methods you’d like remote client applications to
be able to call.
an
On the client, you specify or infer the signatures of the server methods you’d like
to call.
On both the server and the client, you choose a transport and communication
bc
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.
om
client and server are both .NET applications written by the same company (or companies
sharing common assemblies). Communication typically involves exchanging potentially
complex custom .NET objects that the Remoting infrastructure serializes and deserializes
without needing intervention.
The types for Remoting are in or under System.Runtime.Remoting; the types for Web
Services are under System.Web.Services.
.c
tu
Scope of .Net Technology:
Over the period of time, many software have evolved along with many new technologies
al
getting introduced. In this race, one which caught the people’s interest was .Net. In a very
short time this new technology became the boon for the software developer community
and now it’s been considered as the most growing career option, which clearly indicates
ep
Its growing popularity has made it the first choice of many experienced and fresher and
an
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
bc
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
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.
om
design) in which programmers define not only the data type of a data structure, but also
the types of operations (functions) that can be applied to the data structure.
In this way, the data structure becomes an object that includes both data and functions. In
addition, programmers can create relationships between one object and another. For
example, objects can inherit characteristics from other objects.
.c
tu
al
ep
Abstraction: The process of picking out (abstracting) common features of objects and
procedures.
Class: A category of objects. The class defines all the common properties of the different
bc
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.
om
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
.c
by taking most of its features thus making the program easy to implement and modify.
can understand what to do. The program is divided into small parts called functions and
then it follows a series of computational steps to be carried out in order.
It follows a top-down approach to actually solve a problem, hence the name. Procedures
ep
correspond to functions and each function has its own purpose. Dividing the program into
functions is the key to procedural programming. So a number of different functions are
written in order to accomplish the tasks.
an
In POP, program is divided into small partsIn OOP, program is divided into parts
called functions. called objects.
In POP, Importance is not given to data butIn OOP, Importance is given to the data rather
to functions as well as sequence of actions to
than procedures or functions because it works
be done. as a real world.
POP follows Top Down approach. OOP follows Bottom Up approach.
POP does not have any access specifier. OOP has access specifiers named Public,
Private, Protected, etc.
In POP, Data can move freely from function In OOP, objects can move and communicate
to function in the system. with each other through member functions.
To add new data and function in POP is not OOP provides an easy way to add new data and
so easy. function.
om
.c
tu
al
ep
an
bc
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
om
.c
Writing higher-level functions that call upon lower-level functions simplifies a pro‐ gram.
tu
We can refactor our program with a reusable method that multiplies an integer by 12 as
follows:
al
ep
an
bc
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.
om
An identifier must be a whole word, essentially made up of Unicode characters starting
with a letter or underscore. C# identifiers are case-sensitive. By convention, parameters,
.c
local variables, and private fields should be in camel case (e.g., myVariable), and all other
identifiers should be in Pascal case (e.g., MyMethod).
tu
Keywords are names that mean something special to the compiler. These are the keywords
in our example program:
al
Most keywords are reserved, which means that you can’t use them as identifiers. Here is
ep
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:
om
.c
tu
Literals, Punctuators, and Operators
Literals are primitive pieces of data lexically embedded into the program. The literals we
al
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).
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:
om
.c
A variable denotes a storage location that can contain different values over time. In
tu
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
al
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:
In C#, predefined types (also referred to as built-in types) are recognized with a C#
om
keyword. The System namespace in the .NET Framework contains many important types
that are not predefined by C# (e.g., DateTime).
.c
Just as we can build complex functions from simple functions, we can build complex types
from primitive types. In this example, we will define a custom type named UnitConverter
— a class that serves as a blueprint for unit conversions:
tu
al
ep
an
bc
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.
Implicit conversions are allowed when both of the following are true:
The compiler can guarantee they will always succeed.
om
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.
Reference types
Generic type parameters
Pointer types
ep
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.
an
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
bc
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:
om
.c
tu
al
ep
an
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
bc
to an object that contains the value. Here is the Point type from our previous example
rewritten as a class, rather than a struct.
om
.c
tu
al
Numeric Conversions
Converting between integral types
Integral type conversions are implicit when the destination type can represent every
ep
possible value of the source type. Otherwise, an explicit conversion is required. For
example:
an
bc
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
om
a decimal type must be explicit.
Operators in C #:
1. Arithmetic Operators
2.
3.
Relational Operators
Logical Operators .c
tu
4. Bitwise Operators
5. Assignment Operators
6. Miscellaneous Operators
al
Arithmetic Operators
ep
Following table shows all the arithmetic operators supported by C#. Assume
variable A holds 10 and variable B holds 20 then:
an
== 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)
om
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.
<
.c
Checks if the value of left operand is less than the value of right (A < B) is
tu
operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
al
<= 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.
an
Logical Operators
bc
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.
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,
om
operands. which is
0000 1100
.c which
0011 1101
is
tu
^ Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49,
not both. which is
al
0011 0001
~ Binary Ones Complement Operator is unary and has the effect (~A ) = 61,
ep
complement
due to a
signed
bc
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
om
+= Add AND assignment operator, It adds right operand to the left C += A is
operand and assign the result to left operand equivalent
to C = C +
.c A
tu
-= Subtract AND assignment operator, It subtracts right operand C -= A is
from the left operand and assign the result to left operand equivalent
to C = C - A
al
with the left operand and assign the result to left operand equivalent
to C = C *
A
an
Miscellaneous Operators
om
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;
om
Escape sequences express characters that cannot be expressed or interpreted literally. An
escape sequence is a backslash followed by a character with a special meaning. For
example:
.c
tu
The escape sequence characters are shown below.
al
ep
an
bc
The \u (or \x) escape sequence lets you specify any Unicode character via its four-digit
hexadecimal code:
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:
om
.c
The cost of this is that whenever you need a literal backslash, you must write it twice:
tu
To avoid this problem, C# allows verbatim string literals. A verbatim string literal is prefixed
al
with @ and does not support escape sequences. The following verbatim string is identical
to the preceding one:
ep
an
bc
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.
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
om
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:
.c
tu
al
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
ep
to 4:
an
An array initialization expression lets you declare and populate an array in a single step:
bc
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:
Example Program,
om
.c
tu
al
ep
an
bc
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):
om
.c
tu
al
ep
an
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.
om
local variable, parameter (value, ref, or out), field (instance or static), or array element.
This method is recursive, meaning that it calls itself. Each time the method is entered, a
an
new int is allocated on the stack, and each time the method exits, the int is deallocated.
Heap
bc
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.”
Definite Assignment
.c
C# enforces a definite assignment policy. In practice, this means that outside of an unsafe
tu
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.
al
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:
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:
om
You can obtain the default value for any type with the default keyword,
.c
tu
Parameters
A method has a sequence of parameters. Parameters define the set of arguments that must
al
be provided for that method. In this example, the method Foo has a single parameter
named p, of type int:
ep
an
bc
You can control how parameters are passed with the ref and out modifiers:
om
Assigning p a new value does not change the contents of x, since p and x reside in different
memory locations.
.c
tu
The ref modifier
To pass by reference, C# provides the ref parameter modifier. In the following example, p
and x refer to the same memory locations:
al
ep
an
bc
om
The params modifier .c
tu
The params parameter modifier may be specified on the last parameter of a method so
that the method accepts any number of arguments of a particular type. The parameter
type must be declared as an array. For example:
al
ep
an
bc
Optional parameters
A parameter is optional if it specifies a default value in its declaration:
Left-associative operators
om
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:
.c
tu
al
Right-associative operators
ep
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:
an
bc
Null Operators
C# provides two operators to make it easier to work with nulls: the null coalescing operator
and the null-conditional operator.
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
om
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:
.c
tu
A constant declaration is like a variable declaration, except that it cannot be changed after
al
it has been declared, and the initialization must occur with the declaration.
ep
an
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:
bc
om
.c
tu
Note: Please change the syntax of the program.
al
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
ep
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 –
an
Following is an example –
bc
om
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;
.c
tu
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:
al
ep
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.
an
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
bc
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:
Here is a program that uses an if-else-if ladder to determine which season a particular
om
month is in.
.c
tu
al
ep
an
bc
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:
om
.c
tu
al
ep
an
bc
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.
om
.c
tu
al
ep
an
bc
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.
om
.c
tu
al
ep
do while loop
an
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 –
bc
Example
.c
of enumerating over the characters in a string, from the first character through to the last:
tu
al
ep
Output:
10
20
30
40
50
om
.c
tu
al
Jump Statements
ep
The C# jump statements are break, continue, goto, return, and throw. These statements
transfer control to another part of your program.
Using break
an
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.
bc
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
ep
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
an
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.
bc
Here is an example program that uses continue to cause two numbers to be printed on
each line:
Example:
om
.c
tu
Output:
Sum of two numbers=25
al
form is as follows:
an
bc
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:
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:
om
The dots in the namespace indicate a hierarchy of nested namespaces. The code that
follows is semantically identical to the preceding example:
.c
tu
al
ep
an
om
Names declared in outer namespaces can be used unqualified within inner name‐ spaces.
In this example, Class1 does not need qualification within Inner:
.c
tu
al
ep
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:
an
bc
We can even break the example into two source files such that we could compile each class
om
into a different assembly.
.c
tu
al
ep
You can nest a using directive within a namespace. This allows you to scope the using
directive within a namespace declaration. In the following example, Class1 is visible in one
scope, but not in another:
bc
om
.c
tu
al
ep
an
The application cannot compile, because Widget is ambiguous. Extern aliases can resolve
bc
}}
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
om
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
.c
the (:). A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class,
tu
if any, preceded by the (:). A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
al
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
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
om
easily removed and replaced.
A new object t from the class "tree" is created using the following syntax:
Tree t = new Tree ().
Fields .c
tu
A field is a variable that is a member of a class or struct. For example:
class Octopus
{
al
string name;
public int Age = 10;
ep
om
Expression-bodied methods
.c
A method that comprises a single expression, such as the following:
tu
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:
al
Overloading methods
A type may overload methods (have multiple methods with the same name), as long as
an
the signatures are different. For example, the following methods can all coexist in the same
type:
bc
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:
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
om
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 –
.c
tu
Instance Constructors
Constructors run initialization code on a class or struct. A constructor is defined like a
al
method, except that the method name and return type are reduced to the name of the
enclosing type:
ep
an
bc
When one constructor calls another, the called constructor executes first.
Destructor
om
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:
.c
tu
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
al
Syntax
//destructor
om
~ConsDes()
{
Console.WriteLine("This is a destructor");
Console.ReadKey();
}
}
.c
tu
class Construct
{
static void Main(string[] args)
al
{
string msg = "This is a constructor";
ep
Output:
This is a constructor
bc
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.
om
Example
class User
{
// Static Constructor
static User()
{
.c
Console.WriteLine("I am Static Constructor");
tu
}
// Default Constructor
public User()
al
{
Console.WriteLine("I am Default Constructor");
}
ep
}
class Program
{
an
om
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; .c
tu
public Student(int id, String name, int age, String subject) {
this.id = id;
this.name = name;
al
this.subject = subject;
this.age = age;
}
ep
class StudentDetails {
public static void Main(string[] args) {
bc
std1.showInfo();
}
}
Output:
001 Jack 23 Maths
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.
om
.c
tu
al
ep
an
bc
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:
class Test
{
static void Main()
{
Chk obj = new Chk();
obj.a = 10;
om
obj.b = 5;
Console.WriteLine("Sum of "+obj.a+" and "+obj.b+" = "+obj.sum);
Console.ReadKey();
}
}
Output: .c
tu
Sum of 10 and 5 = 15
al
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
ep
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.
<modifier>
om
can be private, public, protected or internal.
<return type>
can be any valid C# types.
this
.c
this is a special keyword in C# to indicate the object of the current class.
tu
[argument list]
The formal-argument-list specifies the parameters of the indexer.
al
om
Syntax of static class
.c
tu
Static members of a class
al
If we declare any members of a class as static we can access it without creating object of
that class.
Example
ep
an
bc
om
.c
tu
al
ep
an
Output
The details of Author is:
Author name : Ankita
Language : CSharp
bc
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:
om
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
o .c
Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
tu
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
al
You can use the same fields and methods already defined in the previous class.
}
The : indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
In the terminology of C#, a class which is inherited is called a parent or superclass,
and the new class is called child or subclass.
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.
Note: Codes are written in Java, So please change the syntax of the program according
ep
to C# language.
1. Single Inheritance
an
Single Inheritance refers to a child and parent class relationship where a class extends the
another class.
class A
bc
{
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);
}
}
2. Multilevel Inheritance
Multilevel inheritance refers to a child and parent class relationship where a class extends
om
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
{
bc
class A7 : A6
{
public void Sub()
{
base.c = base.a - base.b;
Console.WriteLine("Difference=" + base.c);
}
class Level
{
static void Main()
{
A7 obj = new A7();
obj.ReadData(20,5);
obj.Display();
obj.Add();
obj.Sub();
Console.ReadLine();
}
om
}
3. Hierarchical Inheritance
Hierarchical inheritance refers to a child and parent class relationship where more than
.c
one classes extends the same class. For example, classes B, C & D extends the same class
A.
tu
class Polygon
{
public int dim1,dim2;
al
this.dim2 = dim2;
}
}
an
{
base.ReadDimension(10,5);
int area = base.dim1 * base.dim2;
Console.WriteLine("Area of Rectangle="+area);
}
}
//driver class
class Hier
{
static void Main()
{
Traingle tri = new Traingle();
//tri.ReadDimension(10,5);
tri.AreaTri();
om
Console.ReadLine();
}
}
4. Multiple Inheritance
.c
When one class extends more than one classes then this is called multiple inheritance. For
tu
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance.
al
C# doesn’t allow multiple inheritance. We can use interfaces instead of classes to achieve
the same purpose.
ep
interface IA
{
// doesn't contain fields
an
int CalculateArea();
int CalculatePerimeter();
}
bc
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;
//driver class
class Inter
{
static void Main(string[] args)
{
BB obj = new BB();
om
//int area=obj.CalculateArea();
//int peri=obj.CalculatePerimeter();
.c
Console.WriteLine("Perimeter of Rectangle=" +
obj.CalculatePerimeter());
tu
Console.ReadKey();
}
}
al
Interface in C#
ep
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
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).
bc
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.
class BB : IA
{
int l, b;
public void GetData(int l, int b)
{
this.l = l;
this.b = b;
}
public int CalculateArea()
om
{
int area=l*b;
return area;
}
//driver class
ep
class Inter
{
static void Main(string[] args)
{
an
obj.CalculatePerimeter());
Console.ReadKey();
}
}
Output:
Area of Rectangle=50
Perimeter of Rectangle=30
om
.c
tu
al
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
ep
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.
an
The abstract method is declared by adding the abstract modifier the method.
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
} }
Another Example
om
.c
tu
al
ep
an
bc
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.
om
Method Overloading
.c
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
tu
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:
al
a) Number of parameters.
ep
add(int, int)
add(int, int, int)
b) Data type of parameters.
an
add(int, int)
add(int, float)
c) Sequence of Data type of parameters.
add(int, float)
bc
add(float, int)
om
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
.c
different purpose. This method is also used to enforce some must implement features in
derived classes.
tu
Important points:
Method overriding is only possible in derived classes, not within the same class
al
{
return 10;
}
}
Output:
Balance is 500
Virtual Method
om
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
.c
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.
tu
Features of virtual method
By default, methods are non-virtual. We can't override a non-virtual method.
al
We can't use the virtual modifier with the static, abstract, private or override
modifiers.
ep
class Vir
{
bc
class Program
{
static void Main(string[] args)
{
Vir obj = new Vir();
obj.message();
Console.ReadKey();
}
}
class Vir
{
public virtual void message()
{
Console.WriteLine("This is test");
}
}
om
Console.WriteLine("This is test1");
}
}
class Program
{
static void Main(string[] args) .c
tu
{
Vir1 obj = new Vir1();
obj.message();
al
Console.ReadKey();
}
ep
Output:
This is test1
an
om
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 .c
tu
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.
al
if (a is Stock)
Console.WriteLine (((Stock)a).SharesOwned);
ep
Operator Overloading
The concept of overloading a function can also be applied to operators. Operator
an
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
bc
Syntax:
access specifier className operator Operator_symbol (parameters)
{
// Code
}
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.
om
.c
tu
al
ep
an
bc
om
.c
tu
al
ep
an
bc
om
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.
.c
tu
al
ep
an
bc
om
Console.WriteLine(base.color); //displays white
Console.WriteLine(color); //displays black
}
}
public class TestBase
.c
tu
{
public static void Main()
al
{
Dog d = new Dog();
d.showColor();
ep
}
}
an
Output:
Value of a=10 and b=5
Value of x=10 and y=5
om
Calling a base class method which is overridden in derived class
class Base
{
public virtual void BaseMethod()
{
} .c
Console.WriteLine("I am inside base class");
tu
}
class Derived : Base
{
al
base.BaseMethod();
Console.WriteLine("I am inside derived class");
}
}
an
class BaseEx
{
static void Main(){
bc
Output:
I am inside base class
I am inside derived class
om
Boxing and Unboxing
.c
Boxing is the act of converting a value-type instance to a reference-type instance. The
reference type may be either the object class or an interface.
tu
In this example, we box an int into an object:
int x = 9;
object obj = x; // Box the int
al
Unboxing reverses the operation, by casting the object back to the original value type:
int y = (int)obj; // Unbox the int
ep
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.
an
For instance, the following throws an exception, because long does not exactly match int:
bc
System.Type has properties for such things as the type’s name, assembly, base type, and
so on. For example:
om
.c
tu
al
ep
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.
an
om
Access Modifiers .c
tu
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
al
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.
om
.c
tu
al
ep
an
bc
om
.c
tu
al
ep
an
bc
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
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.
om
public class TestClass<T> { }
using System.Collections.Generic;
class Test<T>
bc
{
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");
}
}
class GenericEx
{
static void Main()
{
Test<int> obj = new Test<int>();
om
obj.addItem(10);
obj.addItem(20);
obj.addItem(30);
obj.addItem(40);
obj.addItem(50);
//obj.addItem(60); //overflow exists
obj.displayItem(); .c
tu
Console.ReadKey();
}
}
al
Output
ep
Item at index 0 is 10
Item at index 1 is 20
Item at index 2 is 30
Item at index 3 is 40
an
Item at index 4 is 50
Generic Methods
bc
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.
om
.c
tu
Output
Before swap: 40, 60
al
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
an
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,
bc
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");
//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
om
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
.c
under the Sysyem.Collection namespace. The following table defines the key members;
tu
System.Collection.Queue Members Definition
Enqueue() Add an object to the end of the queue.
Dequeue() Removes an object from the beginning of the
al
queue.
Peek() Return the object at the beginning of the queue
ep
using System.Collections.Generic;
class Program {
an
queue1.Enqueue("MBA");
queue1.Enqueue("BCA");
queue1.Enqueue("BBA");
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;
om
Contains() Returns true if a specific element is found in the
collection.
Clear() Removes all the elements of the collection.
Peek() Previews the most recent element on the stack.
Push()
Pop() .c
It pushes elements onto the stack.
Return and remove the top elements of the
tu
stack.
class Program {
al
stack1.Push("************");
stack1.Push("MCA");
stack1.Push("MBA");
stack1.Push("BCA");
an
stack1.Push("BBA");
stack1.Push("***********");
stack1.Push("**Courses**");
bc
stack1.Push("***********");
Console.WriteLine("The elements in the stack1 are
as:");
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);
om
numberList.Add(21);
numberList.Add(45);
numberList.Add(11);
numberList.Add(89);
// List of string
.c
List<string> authors = new List<string>(5);
authors.Add("Mahesh Chand");
tu
authors.Add("Chris Love");
authors.Add("Allen O'neill");
al
authors.Add("Naveen Sharma");
authors.Add("Monica Rathbun");
authors.Add("David McCarter");
ep
// Collection of string
string[] animals = { "Cow", "Camel", "Elephant" };
an
Console.WriteLine(a);
Remove Elements
// Remove an item
authors.Remove("New Author1");
Sorting
authors.Sort();
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");
om
Removal
// Remove an item
personList.Remove("New Author1");
Sorting
personList.Sort();
ep
Other Methods
personList.Insert(1,"Shaijal"); //insert item at index 1
personList.Count; //returns total items
an
bc
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
om
parameter list and return type and then calls the method in a program for execution when
it is needed.
Declaring Delegates
.c
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
tu
matches with the delegate declaration.
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
al
modifier: It is the required modifier which defines the access of delegate and it is optional
to use.
ep
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.
Transformer is compatible with any method with an int return type and a single int
om
parameter, such as this:
static int Square (int x) { return x * x; }
or
static int Square (int x) => x * x;
.c
Assigning a method to a delegate variable creates a delegate instance:
Transformer t = new Transformer (Square);
tu
Or
Transformer t = Square;
al
{
static int MyMethod(int x)
{
bc
return x * x;
}
Output:
Result is : 25
using System;
class TestDelegate {
static int num = 10;
om
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
.c
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
tu
//calling the methods using the delegate objects
nc1(25);
al
Output:
Value of Num: 35
Value of Num: 175
bc
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);
}
// Main Method
public static void Main(String[] args)
{
addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);
om
// "Invoke" method
// del_obj1.Invoke(100, 40);
// del_obj2.Invoke(100, 60);
}
}
Output: .c
tu
(100 + 40) = 140
(100 - 60) = 40
al
Multicast Delegates
All delegate instances have multicast capability. This means that a delegate instance can
ep
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;
an
Invoking d will now call both SomeMethod1 and SomeMethod2. Delegates are invoked in
the order they are added.
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.
using System;
om
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc;
.c
NumberChanger nc1 = new NumberChanger(AddNum);
tu
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
al
nc += nc2;
//calling multicast
ep
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
an
Output
Value of Num: 75
bc
om
Above class methods are used using delegate,
.c
tu
al
ep
an
bc
Output
Instance Method
Static Method
So using delegate, we can associate instance and static method under same delegate
instance.
om
6 When you access the method using When you access the method you
delegates you do not require any access need the object of the class which
to the object of the class where the implemented an interface.
method is defined.
7
8
It does not support inheritance.
It created at run time.
.cIt supports inheritance.
It created at compile time.
tu
9 It can implement any method that If the method of interface
provides the same signature with the implemented, then the same name
given delegate. and signature method override.
al
10 It can wrap any method whose signature A class can implement any number of
is similar to the delegate and does not interfaces, but can only override those
consider which from class it belongs. methods which belongs to the
ep
interfaces.
Delegate Compatibility
an
Type compatibility
Delegate types are all incompatible with one another, even if their signatures are the same:
bc
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.
om
.c
tu
al
ep
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.
an
This is ordinary polymorphic behaviour. For exactly the same reason, a delegate’s target
method may return a more specific type than described by the dele‐ gate. This is called
covariance. For example:
With this definition, we can write a generalized Transform utility method that works on
any type:
om
.c
tu
al
The Func and Action generic delegates were introduced in the .NET Framework version 3.5.
Whenever we want to use delegates in our examples or applications, typically we use the
following procedure:
an
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.
class MethodCollections
{
//Methods that takes parameters but returns nothing:
om
for (int i = start; i <= target; i++)
{
Console.Write(" {0}",i);
}
Console.WriteLine();
}
.c
public static void Print(string message)
{
tu
Console.WriteLine(message);
}
al
{
return a + b;
}
an
}
public static int ShowNumber()
{
Random r = new Random();
return r.Next();
}
}
om
Console.WriteLine("\n***************** Action<> Delegate Method
***************\n");
printText(); //Parameter: 0 , Returns: nothing
print("Abhishek"); //Parameter: 1 , Returns: nothing
Console.WriteLine();
.c
printNumber(5, 20); //Parameter: 2 , Returns: nothing
Console.ReadLine();
}
bc
om
5. An Event can have so many subscribers.
6. Events are basically used for the single user action like button click.
7. If an Event has multiple subscribers then event handlers are invoked synchronously.
Declaring Events
.c
To declare an event inside a class, first of all, you must declare a delegate type for the even
as:
tu
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
an
like below:
public delegate void MyEventHandler(object sender, EventArgs e);
bc
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;
om
static void Main(string[] args)
{
.c
add += new DelEventHandler(India);
add += new DelEventHandler(England);
add.Invoke();
tu
Console.ReadLine();
}
al
}
ep
using System;
an
using System.Drawing;
using System.Windows.Forms;
//custom delegate
bc
public Program()
{
// design a button over form
Button btn = new Button();
btn.Parent = this;
btn.Text = "Hit Me";
btn.Location = new Point(100,100);
om
}
static void Main(string[] args)
{
Application.Run(new Program());
}
Console.ReadLine();
.c
tu
}
al
ep
an
bc
delegate(parameter_list){
// Code..
};
Example:
using System;
om
class GFG {
// Main method
static public void Main()
{ .c
tu
// An anonymous method with one parameter
petanim p = delegate(string mypet)
al
{
Console.WriteLine("My favorite pet is: {0}",
mypet);
ep
};
p("Dog");
}
}
an
Output:
My favorite pet is: Dog
bc
om
input => { statements };
class LambdaTest
{
static int test1() => 5; .c
tu
static int test2(int x) => x + 10;
{
int x=test1();
int res = test2(x);
ep
Output:
Result is: 15
om
.c
tu
al
ep
Throwing Exceptions
Exceptions can be thrown either by the runtime or in user code. In this example, Display
throws a System.ArgumentNullException:
om
.c
tu
al
ep
an
Re-throwing an exception
You can capture and re-throw an exception as follows:
bc
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.
om
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 .c
tu
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.
al
System.NotImplementedException
Thrown to indicate that a function has not yet been implemented.
ep
System.ObjectDisposedException
Thrown when the object upon which the function is called has been disposed.
an
bc
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.
om
.c
tu
al
ep
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.
an
bc
The following example demonstrates a simple LINQ query that gets all strings from an
array which contains 'a'.
om
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.
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
ep
"Java"
};
}
}
Output:
2 4 6
Example 2
using System;
om
using System.Collections.Generic;
using System.Linq;
class Dog
{
public string Name { get; set; }
}
public int Age { get; set; }
class demo{ .c
tu
static void Main()
{
List<Dog> dogs = new List<Dog>() {
al
};
var names = dogs.Select(x => x.Name);
foreach (var name in names)
{
an
Console.WriteLine(name);
}
bc
Console.Read();
}
}
Output:
Rex
Sean
Stacy
Output:
Dog Rex is 4 years old.
Dog Stacy is 3 years old.
Dog Sean is 0 years old.
LINQ Operators
om
Filtering Where, OfType
Sorting OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Grouping GroupBy, ToLookup
Join
Projection
GroupJoin, Join
Select, SelectMany .c
tu
Aggregation Aggregate, Average, Count, LongCount, Max, Min, Sum
Quantifiers All, Any, Contains
al
om
//Multiple Condition
var result = names.Where(s=>s.Contains("Ram") ||
s.Contains("Gita"));
foreach (string val in result)
{
Console.WriteLine(val); .c
tu
}
Console.ReadLine();
al
}
}
}
ep
Output:
Ram
Gita
an
{
public int sid { get;set;}
public string name { get; set; }
public string address { get; set; }
class LinqTest
{
static void Main(string[] args)
Console.WriteLine(res.sid+"\t"+res.name+"\t"+res.address);
}
om
Console.ReadLine();
}
}
Output:
Sid
1
Name
Ram
Address
Btm .c
tu
Joining multiple lists – (join, concat, union)
class LinqTest
al
{
static void Main(string[] args)
ep
{
List<string> names = new List<string>() {
"Ram","Shyam","Hari"};
List<string> address = new List<string>()
an
{"Btm","Ktm","Btm" };
/*using join
var result = names.Join(address,
bc
//using union
var result = names.Union(address);
foreach (var res in result)
{
Console.WriteLine(res);
}
Console.ReadLine();
} }
Console.WriteLine("Maximum marks="+max);
Console.WriteLine("Minimum marks=" + min);
Console.WriteLine("Sum of marks=" + sum);
Console.WriteLine("Total Count=" + total);
om
Console.ReadLine();
}
}
class Student .c
tu
{
public int sid { get; set; }
public string name { get; set; }
al
{
this.sid = sid;
this.name = name;
an
this.address = address;
}
}
bc
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.ReadLine();
}
}
Output
Max Id=4
Total Students=4
Using Order By
class Student
{
public int sid { get; set; }
public string name { get; set; }
om
public string address { get; set; }
class LinqTest
{
ep
};
Console.WriteLine("Name\tAddress");
foreach (var res in result)
{
Console.WriteLine(res.name + "\t" + res.address);
}
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; }
om
public Student(int sid, string name, string address)
{
this.sid = sid;
}
this.name = name;
this.address = address;
.c
tu
}
class LinqTest
al
{
static void Main(string[] args)
ep
{
List<Student> mylist = new List<Student>(){
new Student(1,"Ram","Btm"),
new Student(2, "Hari", "Ktm"),
an
new Student(3,"Shyam","Btm"),
new Student(4, "Gita", "Ktm")
};
bc
Console.WriteLine(res.sid+"\t"+res.name+"\t"
+ res.address);
}
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
om
.c
tu
al
ep
an
bc
ADO : ActiveX Data Objects and ADO.Net are two different ways to access database in
om
Microsoft.
ADO ADO.Net
ADO is base on COM : Component Object ADO.Net is based on CLR : Common
Modelling based. Language Runtime based.
ADO can’t be integrated with XML because ADO.Net can be integrated with XML as
al
by DataSet or DataAdapter.
ADO is connection oriented means it requires ADO.Net is disconnected, does not need
an
ADO gives rows as single table view, it scans ADO.Net gives rows as collections so you can
bc
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.
om
SqlConnection connection;
SqlCommand command;
String conn_str="Data Source=Raazu\\SQLEXPRESS; Initial
Catalog=billing; User ID=sa;Password=24518300";
connection = new SqlConnection(conn_str);
connection.Open();
.c
tu
String sql = "insert into tblCustomer(name,address) values(“Raaju”,
“Birtamode”)";
al
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
ep
For MS-Access
Note: Access Database Engine must be installed
an
OleDbConnection conn;
OleDbCommand command;
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\\Users\\Raazu\\Documents\\Visual Studio
bc
2012\\Projects\\DatabaseTest\\testdb.accdb";
conn = new OleDbConnection(constr);
conn.Open();
om
between tables. It is used to hold multiple tables with data. You can select data form tables,
create views based on table and ask child rows over relations. Also DataSet provides you
with rich features like saving data as XML and loading XML data.
//Example
DataSet ds = new DataSet();
da.Fill(ds);
.c
tu
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.
al
//Example
ep
DataAdapter
- Lets you close the connection as soon it's done loading data, and may even close it
for you automatically
bc
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);
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
om
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.
namespace DatabaseTest
{
class Program
ep
{
OleDbConnection conn;
OleDbCommand command;
an
void CreateConnection()
{
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\\Users\\Raazu\\Documents\\Visual Studio
bc
2012\\Projects\\DatabaseTest\\testdb.accdb";
conn = new OleDbConnection(constr);
conn.Open();
}
om
Program obj = new Program();
try
{
obj.CreateConnection();
4.Select");
.c
x: Console.WriteLine("1.Insert\t 2.Update\t 3.Delete\t
switch (n)
{
case 1:
ep
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);
om
Console.ReadKey();
}
}
Connect C# to MySQL .c
tu
First make sure you have downloaded and installed the MySQL Connector/NET
from the MySQL official website.
Add reference MySql.Data in your project.
al
using MySql.Data.MySqlClient;
ep
namespace DatabaseTest
{
class Program
{
MySqlConnection conn;
MySqlCommand command;
void CreateConnection()
{
string constr = "SERVER=localhost; DATABASE=dbtest;
UID=root; PASSWORD=;";
conn = new MySqlConnection(constr);
conn.Open();
}
om
{
string sid = dt.Rows[i]["sid"].ToString();
string name = dt.Rows[i]["name"].ToString();
string address = dt.Rows[i]["address"].ToString();
}
}
.c
Console.WriteLine(sid+"\t"+name+"\t"+address);
tu
}
{
Program obj = new Program();
try
ep
{
obj.CreateConnection();
x: Console.WriteLine("1.Insert\t 2.Update\t 3.Delete\t
4.Select");
an
switch (n)
{
case 1:
Console.WriteLine("Ënter Name of Student: ");
nm = Console.ReadLine();
Console.WriteLine("Ënter Address of Student: ");
add = Console.ReadLine();
sql = "INSERT INTO tblStudent (name,address)
VALUES('"+nm+"','"+add+"')";
obj.InsertUpdateDelete(sql);
break;
case 2:
Console.WriteLine("Enter id to be updated");
id = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ënter Name of Student: ");
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";
om
obj.SelectRecords(sql);
break;
default:
.c
Console.WriteLine("Wrong Choice");
break;
tu
}
goto x;
}
al
Console.ReadKey();
}
}
}
bc
om
if (dt.Rows.Count != 0)
{
Console.WriteLine("Sid\t Name\t Address");
for (int i = 0; i < dt.Rows.Count;i++)
{
.c
string sid = dt.Rows[i]["sid"].ToString();
string name = dt.Rows[i]["name"].ToString();
tu
string address = dt.Rows[i]["address"].ToString();
Console.WriteLine(sid+"\t"+name+"\t"+address);
}
al
}
}
ep
{
obj.CreateConnection();
x: Console.WriteLine("1.Insert\t 2.Update\t 3.Delete\t
4.Select");
bc
case 3:
Console.WriteLine("Enter id to be deleted");
id = Convert.ToInt32(Console.ReadLine());
sql = "DELETE FROM tblStudent WHERE sid="+id;
obj.InsertUpdateDelete(sql);
om
break;
case 4:
sql = "SELECT * FROM tblStudent";
.c
obj.SelectRecords(sql);
break;
tu
default:
Console.WriteLine("Wrong Choice");
al
break;
}
goto x;
ep
}
catch (Exception ex)
{
Console.WriteLine(ex);
an
Console.ReadKey();
}
}
}
Basic Controls:
om
The following table lists some of the commonly used controls:
1 Forms
.c
The container for all the controls that make up the user interface.
tu
2 TextBox
al
3 Label
4 Button
bc
5 ListBox
6 ComboBox
7 RadioButton
8 CheckBox
9 PictureBox
10 ProgressBar
om
11 ScrollBar
12 DateTimePicker .c
tu
It represents a Windows control that allows the user to select a date and a time
al
and to display the date and time with a specified format.
13 TreeView
ep
14 ListView
bc
It represents a Windows list view control, which displays a collection of items that
can be displayed using one of four different views.
om
need to keep track of the files you need, which ones need to be compiled, and
which need to be deployed.
User interface Your application typically presents information to users; in an
ASP.NET Web application, the user interface is presented in Web Forms pages,
Framework.
Security, performance, and other infrastructure features As in any application,
you must implement security to prevent unauthorized use, test and debug the
an
application, tune its performance, and perform other tasks not directly related to
the application's primary function.
bc
om
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
ep
If you want check box or radio button to be selected when the form is initially displayed,
an
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.
</asp:CheckBox>
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">
om
Launch another form on button click
protected void btnSelect_Click(object sender, EventArgs e)
{
} .c
Response.Redirect("AnotherForm.aspx");
tu
Example 1 – Creating a basic form in ASP.Net
al
ep
an
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>This is my first application</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/>
<asp:Label ID="lblAddress" runat="server" Text="Address:">
</asp:Label>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox> <br/>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</form>
</body>
</html>
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>
om
<br/><br/>
<asp:Label ID="Label2" runat="server" Text="First Number">
</asp:Label>
<asp:TextBox ID="txtSecond" runat="server"></asp:TextBox>
<br/><br/>
.c
<asp:Label ID="lblResult" runat="server" Text="Result:">
</asp:Label> <br/><br/>
tu
<asp:Button ID="btnSubmit" runat="server" Text="Get Result"
onClick="btnSubmit_Click"/>
</div>
al
</form>
EventHandling.cs
ep
om
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")); .c
tu
dropProgram.Items.AddRange(mylist.ToArray());
}
al
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
example.cs
protected void btnSelect_Click(object sender, EventArgs e)
{
if (radioMale.Checked)
lblSelected.Text = "Male Selected";
else
lblSelected.Text = "Female Selected";
}
om
Example – 5 Using Check box
.c
tu
example.aspx
<form id="form1" runat="server">
<div>
al
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";
}
om
Validation Control Description
RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the
RangeValidator
.c
value of another input control or to a fixed value
Checks that the user enters a value that falls
between two values
tu
RegularExpressionValidator Ensures that the value of an input control
matches a specified pattern
al
in a Web page
om
<br/><br/>
.c
runat="server" ControlToValidate="txtClass"
ForeColor="Red"
tu
ErrorMessage="Class must be between (1-12)"
MaximumValue="12"
MinimumValue="1" Type="Integer">
al
</asp:RangeValidator>
<br/><br/>
ep