C# and .NET TECHNOLOGIES notes
C# and .NET TECHNOLOGIES notes
NET Technologies
Syllabus
Unit 1: Introduction to .Net Technologies: Introduction to Web Technologies. HTML Basics, Scripts.
Sample Programs. Advantages and Disadvantages of Client-side and Server-side Scripts. Overview of
Client-side and Overview of Technologies and Server-side Technologies.
Introduction to C#: Overview of C#, Literals, Variables, Data Types, Operators, Expressions, Control
Structures-Methods, Arrays, Strings, Structures, Enumerations.
Unit 2: OOPS with C#: Classes, Objects, Inheritance, Polymorphism, Interfaces, Operator Overloading
Delegates, Events, Errors and Exceptions.
ADO .NET Connectivity: Introduction to ADO.NET, ADO vs ADO.NET. Architecture: Data reader, Data
adopter, Accessing Data with ADO.NET. Programming Web Applications with Web Forms, ASP .NET
applications with ADO.NET
1
Unit 1
Introduction to .NET Technologies
Introduction to Web Technologies
Web Technology:
Web Technology refers to the various tools and techniques that are utilized in the process of
communication between different types of devices over the internet. A web browser is used to access
web pages. Web browsers can be defined as programs that display text, data, pictures, animation, and
video on the Internet.
WWW has allowed for the access of information that would have been impossible to find or may have
been difficult to find without the www.
Internet: The Internet is the massive network of networks that connects millions of computers
worldwide.
WWW: The World Wide Web, abbreviated as WWW and commonly known as the Web, is a system of
interlinked hypertext documents accessed via the Internet. With a web browser, one can view web
pages that may contain text, images, videos, and other multimedia and navigate between them via
hyperlinks.
Computers connected to the Internet can communicate with one another with a number of protocols
such as HTTP, SMTP (Simple Mail Transfer Protocol), FTP (File Transfer Protocol), IRC (Internet relay
chat), IM (instant messaging), Telnet, and P2P (peer-to-peer).
World Wide Web (WWW): The World Wide Web is based on several different technologies: Web
browsers, Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP).
Web Pages: A webpage is a digital document that is linked to the World Wide Web and viewable by
anyone connected to the internet has a web browser.
Website: A collection of web pages which are grouped together and usually connected together in
various ways. Often called a "web site" or simply a "site.“
Web Browser: A web browser takes you anywhere on the internet. It retrieves information from other
parts of the web and displays it on your desktop or mobile device. The information is transferred using
the Hypertext Transfer Protocol, which defines how text, images and video are transmitted on the web.
Examples of Web Browser:- Internet Explorer, Google Chrome, Fire Fox , Safari.
Web Server: A Web server is a program or computer machine that generates and transmits responses
to client requests for Web resources using HTTP protocol. Every computer on the Internet that contains
a Website must have a Web server program.
2
Web Development: Web development refers to the building, creating, and maintaining of websites. It
includes aspects such as web design, web publishing, web programming, and database management. It
is the creation of an application that works over the internet i.e. websites.
Static pages show the same content each time they are viewed. Static web pages are very
simple. It is written in languages such as HTML, JavaScript, CSS, etc.
Dynamic pages have content that can change each time they are accessed. Dynamic Web Pages
are written in languages such as CGI, AJAX, ASP, ASP.NET, etc. In dynamic web pages, the
Content of pages is different for different visitors.
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
Internet.
3. file or resource location: These substrings are separated by special characters as follows:
Example: http://www.programiz.com
The client computer will request data or services on the server. Then after the request is received, the
server will process it and the results are sent back to the client computer.
o Obtaining the IP Address from domain name: Our web browser first obtains the IP address
the domain name
o Browser requests the full URL : After knowing the IP Address, the browser now demands a
full URL from the web server.
o Web server responds to request: The web server responds to the browser by sending the
desired pages.
3
IP Address: IP stands for "Internet Protocol,” it is a unique address that identifies a device on the
internet or a local network which is the set of rules governing the format of data sent via the internet or
local network.
The Apache HTTP Server, commonly referred to as Apache is a web server software program which
gave the initial boost for the growth of the World Wide Web. The server is aimed at serving a great deal
of widely popular modern web platforms/operating systems such as Unix, Windows, Linux, Mac OS x
etc.
IIS is one of the components of Microsoft Windows and is Microsoft's implementation of a web server.
The protocols supported include HTTP, HTTPS, FTP, FTPS & SMTP .t's estimated that around 25% of all
websites utilize IIS.
Protocol
A protocol is a set of rules that govern data communications .A protocol defines what is communicated,
how it is communicated, and when it is communicated. It represents an agreement between the
communicating devices.
HTTP stands for Hyper Text Transfer Protocol it is the language of the Web.
HTTP is a protocol used for communication between web browsers and web servers.
When a web page has this prefix, then your links, text, and pictures should work in your web
browser
HTTP functions as a request-response protocol in the client-server computing model.
A web browser, for example, may be the client and an application running on a computer
hosting a web site maybe the server.
The client submits an HTTP request message to the server.
The server, which provides resources such as HTML (Hyper Text Markup Language) files and
other content, or performs other functions on behalf of the client, returns a response message to
the client.
APIs are mechanisms that enable two software components to communicate with each other using a set
of definitions and protocols. In other words, an API is the messenger that delivers your request to the
provider that you're requesting it from and then delivers the response back to you. For example, the
weather bureau's software system contains daily weather data. The weather app on your phone “talks”
to this system via APIs and shows you daily weather updates on your phone.
Gateway
The gateway converts information, data or other communications from one protocol or format to
another. A router may perform some of the functions of a gateway. An Internet gateway can transfer
communications between an enterprise network and the Internet. For example, if a computer on the
Internet sends an email to another, the gateway converts the message from one protocol to another and
sends it back.
4
XML:XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML). XML tags identify the data and are used to store and
organize the data, rather than specifying how to display it like HTML tags, which are used to display the
data.
HTML Basics
HTML stands for Hyper Text Markup Language.
HTML is the standard Markup language for creating Web pages.
HTML describes the structure of a Web page.
HTML consists of a series of elements.
HTML elements tell the browser how to display the content.
HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this is a
link", etc.
HTML uses HTML Tags that are integrated into text document.
HTML has opening tag with respective closing tag.
HTML code can be written in an text editor like Notepad.
Save the file with .htm or .html extension.
Open the file with any web browser to see the html page output.
<!DOCTYPE html>
<html>
<body>
-------------------------
-------------------------
-------------------------
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
5
<p> My first paragraph </p>
</body>
</html>
Attributes in HTML
usually come in Attributes provide additional information about elements. Attributes are
always specified in the start tag. Attributes name/value pairs like: name="value".
The href Attribute: The <a> tag defines a hyperlink. The href attribute specifies the URL of the
page the link goes to.
Example: <a href="https://www.w3schools.com">Visit W3Schools</a>
The src Attribute: The <img> tag is used to embed an image in an HTML page. The src attribute
specifies the path to the image to be displayed.
Example: <img src="img_net.jpg" >
The <img> tag should also contain the width and height attributes, which specify the width and
height of the image (in pixels)
Example: <img src="img_net.jpg" width="500" height="600">
The alternate attribute <alt>: The required alt attribute for the <img> tag specifies an
alternate text for an image.
Example: <img src="img_net.jpg" alt="bca">
<style>: The style attribute is used to add styles to an element, such as color, font, size, and
more.
6
Example: <p style="color: red;">This is a red paragraph.</p>
<lang>: You should always include the lang attribute inside the <html> tag, to declare the
language of the Web page.
Example: <html lang="en">
Hyperlinks
It allows navigation from one page to another page which is used to link from one page to another
page. We use the <a> tag to define a hyperlink. In the <a> tag, the href attribute specifies the URL of the
page the link goes to. The href attribute consists of two components: the URL (actual link) and the
anchor text or clickable text that appears on the page.
Example:
<span> tag: The <span> tag is an inline container used to mark up a part of a text, or a part of a
document.
Example: <p> Computer Science <span style=”color: red; font-weight bolder”>portal</span> for <span
style=”background color light-green;”>students</span>
<div> tag: It helps to separate our data in web page. We can create particular section for particular data
like text, images, header, footer etc. It is used to group large section of elements together.
HTML Tables:
An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements.
The <tr> element defines a table row, the <th> element defines a table header, and the <td> element
defines a table cell.
7
HTML Lists:
HTML lists allows web developers to group a set of related items in lists.
HTML Forms:
The HTML <form> element is used to create an HTML form for user input.
The <form> element is a container for different types of input elements, such as: text fields, checkboxes,
radio buttons, submit buttons, etc.
8
Scripting Language or Scripts
A script or scripting language is a computer language that does not need the compilation step and is
rather interpreted one by one at runtime.
Scripts are often utilized to create dynamic web applications nowadays because they are linked to web
development.
It is embedded in an HTML web page, interpreted, and executed by a certain scripting engine.
Client-Side Scripting.
Server-Side Scripting.
Client-Side Scripting
Client-side means that the processing takes place on the user’s computer. It requires browsers
to run the scripts on the client machine without involving any processing on the server.
The processing takes place on the end users computer. Client will request the server.The source
code is transferred from the web server to the users computer over the internet and run
directly in the browser. This script will allow the client’s browser to alleviate some of the
burden on your web server when running a web application.
Client side scripting cannot be used to connect to the databases on the web server. Client-side
scripting is faster because it does not require interaction with the web server only interaction
done is receiving the data which was requested.
The main tasks of Client side JavaScript are validating input, animation, manipulating UI
elements, applying styles, some calculations are done when you don't want the page to refresh
so often.
Languages used: HTML, CSS, JavaScript, VBScript
9
Server-Side Scripting
Server-side means that the processing takes place on a web server and the script is not visible to
the user.
A user's request is fulfilled by running a script directly on the web server to generate dynamic
HTML pages. This HTML is then sent to the client browser. It is usually used to provide
interactive web sites that interface to databases or other data stores on the server .
It helps to provide response to every request that comes from user client. Server-side scripting
is associated with accessing data, error handling, and the fastest processing of the data. It is
processed and communicates with the server.
Therefore, it is secure. It is generally used to create dynamic websites, send responses to user
queries, or provide data, etc.
The most common and widely used server-side scripting programming language is C#, PHP,
Java, ASP.NET, and many more.
Consider a simple example. Let's say you are completing an online form, and you have to type in your
phone number. Logically, that should only consist of numbers, and it may require a very specific format,
such as this: 5552347890.
The form will not allow you to enter characters that are not numbers, and it will not allow you to use a
different format. This is the result of a client-side script. The script responds immediately to your
typing, checks your input, and provides a response before you actually submit the form.
Consider the example of logging into your bank account online. You can go to the bank's homepage and
fill in your username and password. Then you click the 'login' button. This sends a request to the server.
The server checks your login credentials and pulls up your account information - this is when the
scripts are run. The server then creates an HTML page to present you with your account details.
CLIENT
SERVER
10
Advantages of Scripting Language
Open source and Free: First, they are open source. Therefore, anyone around the world can
use it and contribute to it.
Easy to use: Second, if you are a beginner, they are a great way to start with programming
languages, as they are quite easy to learn and code.
Lighter memory requirement: As we know that most scripting languages use an interpreter,
and unlike compilers, no executable file is stored, and hence, they require less memory.
Portable and platform Independent: They are portable, i.e., can run on different operating
systems.
Interactivity: It helps to make web pages more interactive by adding combinations and
visualization interfaces. The use of scripting languages is demanded by modern web pages. It
includes background and foreground colors and so on, which helps to create enhanced web
pages.
Scripts are also used as a prototype before building an actual program.
It directly executes the files without needing compilation but sometimes may be required
to compile when necessary.
Functionality: Scripting languages contain different libraries, which help to create new
applications in web browsers. They are different from normal programming languages.
It enables users to view and code that may be prohibited by some companies.
These languages did not compile the file and interpret it directly, which need to install an
interpreter or separate program by the users before running the script.
Compared with a compiled program, scripting languages may be slow in some situations.
In the scripting languages, the interpreter analyzes each statement line by line during execution,
therefore don’t perform many optimizations to execute the code faster.
One main disadvantage of the graphic user interface is that they are expensive and takes much
time to develop.
It is not supported by all browsers. if no alternative is given for the script than the user might
get an error.
Sample Programs
<html>
<body>
<script language= “javascript” type “text/javascript>
document.write (“hello world”);
</script>
</body>
</html>
Each of the below method have different ways of outputting the content.
console.log () for debugging the javascript code.
11
document.write() is used when we want to print the content/output.
alert ()
12
Overview of Client-Side Technologies
Javascript: JavaScript is a famous scripting language used to create magic on the sites to make
the site interactive for the user.
VBScript: VBScript (Visual Basic Script) is a general-purpose, lightweight and active scripting
language mainly used to give functionality to webpages.
HTML: HTML stands for Hypertext Markup Language. It is used to design the front-end portion
of web pages using a markup language.
CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed language intended to
simplify the process of making web pages presentable. CSS allows you to apply styles to web
pages.
AJAX : Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with
the server without refreshing the web page and thus increasing the user experience and better
performance.
JQuery : jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery
is to make it much easier to use JavaScript on your website.
13
Introduction to C#
Features of C#
Simple: C# is a simple language in the sense that it provides structured approach (to break the
problem into parts).
Modern programming language: C# programming is based upon the current trend and it is
very powerful and simple for building scalable, interoperable and robust applications.
Object oriented: C# is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is not easy to
manage if code grows as project size grow.
Type safe: C# is type safe code can only access the memory location that it has permission to
execute. Therefore it improves a security of the program
Interoperability: Interoperability process enables the C# programs to do almost anything that
a native C++ application can do.
Scalable and Updateable: C# is automatic scalable and updateable programming language. For
updating our application we delete the old files and update them with new ones.
Structured programming language: C# is a structured programming language in the sense
that we can break the program into parts using functions. So, it is easy to understand and
modify.
Rich Library: C# provides a lot of inbuilt functions that makes the development fast.
Fast speed: The compilation and execution time of C# language is fast.
Applications of C#
Games using Unity
Web Applications Client-Server Applications
Windows Applications: Applications that run on desktops
Web Services Applications
Console Applications
Class Libraries
14
Difference between C++ and C#
C# Program Structure
C# Program Syntax
using System;
namespace <namespace_name>
{
class <class_name>
{
static void Main(string[] args)
{
---------------------------
---------------------------
}
}
}
using System;
namespace Sample
{
class Program {
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}}
15
A C# program consists of the following parts:
The first line of the program using System; - the using keyword is used to include the System
namespace in the program. Any construct used in program is defined within System namespace.
The next line has the namespace declaration. A namespace is a collection of classes. The Sample
namespace contains the class Program.
C# is an object-oriented programming language hence at least one class must be defined. The class
Program contains the data and method definitions that your program uses.
The main () is a method of Program class is the entry point of the console application.
static() : There is no object of the class available at the time of runtime, and because of that, we have to
define the main() method as static. To load the class into the memory and call the main method.
void() : The main() method doesn't return anything, and its return type is void. The main() method
doesn't return anything to make things simple.
Console.WriteLine is a static method which is used to display a text on the console.
Literals
The fixed values are called literals. The constants refer to fixed values that the program may not
alter during its execution.
The fixed values are called as Literal. Literal is a value that is used by the variables. Values can
be either an integer, float or string, etc.
Integer Literals: A literal of integer type is know as the integer literal. It can be octal, decimal, binary,
or hexadecimal constant.
A suffix can also be used with the integer literals like U or u are used for unsigned numbers while l or
are used for long numbers.
Example: int x = 101;
int x = 0146;
int x = 0123F;
int x = 0b101;
Floating-point Literals: The literal which has an integer part, a decimal point, a fractional part, and an
exponent part is known as the floating-point literal.
Example: double d = 3.14145
Character Literals: For character data types we can specify literals in 3 ways:
Single quote: We can specify literal to char data type as single character within single quote.
Example: char ch = 'a';
Unicode Representation: We can specify char literals in Unicode representation ‘\uxxxx’. Here xxxx
represents 4 hexadecimal numbers.
16
Example: char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence: Every escape character can be specified as char literals.
Example: char ch = '\n';
String Literals: Literals which are enclosed in double quotes(“ ”) are known as the String literals
Example: String s1 = "Hello Geeks!";
Boolean Literals: Only two values are allowed for Boolean literals i.e. true and false.
Example: bool a = true;
bool b = false;
The null literal evaluates to the null value, which is used to denote a reference not pointing at any
object or array, or the absence of a value.
Variables
o A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.
o It is a way to represent memory location through symbol so that it can be easily identified.
o Each variable in C# has a specific type, which determines the size and layout of the variable's
memory the range of values that can be stored within that memory and the set of operations
that can be applied to the variable.
17
Invalid variable names:
int 4;
int x y;
int double;
In the above diagram, we can see the Constants are of two types
Compile time constants (const)
Runtime constants (Readonly)
Example:
using System;
class Program {
public const int myvar = 10;
public static void Main()
{
Console.WriteLine("The value of myvar: ", myvar);
}
}
18
int readonly a=10;
int b=1;
int readonly c=a+b;
When readonly is used ?
We can use Readonly when its value is not an absolute constant, which means it can be changed
frequently, such as dollars vs INR.
Example:
using System;
class Prog
{
public readonly int myvar1;
public GFG (int b)
{
myvar1 = b;
Console.WriteLine("Display value of myvar1 ", myvar1);
}
static public void Main()
{
Prog obj1 = new Prog (100);
}
}
Data Types in C#
Data types specify the type of data that a valid C# variable can hold.
19
Value Data Type
In C#, the Value Data Types will directly store the variable value in memory The value data types are
integer-based and floating-point based. C# language supports both signed and unsigned literals.
There are 2 types of value data type in C# language.
1) Predefined Data Types - such as Integer, Boolean, Float, etc.
2) User defined Data Types - such as Structure, Enumerations, etc.
Structure: In C#, a structure is a value type data type. It helps you to make a single variable hold related
data of various data types. The struct keyword is used for creating a structure.
Enumerations: An enumeration is a set of named integer constants. An enumerated type is declared
using the enum keyword
The memory size of data types may change according to 32 or 64 bit operating system.
20
Boxing and Unboxing
The conversion of the value type to the reference type is known as boxing . The boxing is also
considered as the implicit conversion that it is used in any object type.
Example:
Boxing:
int i = 123;
object o = I; // boxing
Example Program:
using System;
class Box
{
static public void Main() // main method
{
int val = 1000;
object obj1 = val; // Boxing technique
val = 500; // the changing of value
Console.WriteLine("Value Typed - The type value of number is : {0}", val);
Console.WriteLine("Object Typed - The type value of obj1 is : {0}", obj1);
}
}
Unboxing
The unboxing in the c# language is vice versa of the Boxing. It is the process of converting the
Reference Type data type variable to the Value Typed data type variable. This entire process is
known as the Unboxing terminology in c#.
The unboxing is also considered as the explicit conversion that it is used in any object type
process.
Example
UnBoxing:
o = 123;
i = (int)o; // unboxing
Example Program:
using System;
class Unbox
{
static public void Main() // Main method
{
int val = 10; // assigning the value 10 to the val
object obj1 = val; // Boxing technique
int i = (int)obj1; // unboxing technique
Console.WriteLine("The Value of obj1 object is : " + obj1); //
Console.WriteLine("The Value of I is : " + i);
}
}
21
Operators in C#
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Miscallenous Operators/Special Operators.
•
Arithmetic Operators:
These are used to perform arithmetic/mathematical operations on operands.
Example:
using System;
namespace Arithmetic
{
class Prog
{
static void Main()
{
int result;
int x = 10, y=20;
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
result = (x - y);
Console.WriteLine("Subtraction Operator: " +
result);
result = (x * y);
Console.WriteLine("Multiplication Operator: "+
result);
}
}
}
Relational Operators:
Relational operators are used to check the relationship between two operands. If the relationship is true
the result will be true, otherwise it will result in false.
Example:
using System;
namespace Relational
{
class Prog
{
static void Main()
{
bool result;
int x = 5, y = 10;
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
result = (x > y);
22
Console.WriteLine("Greater than Operator: " + result);
result = (x < y);
Console.WriteLine("Less than Operator: " + result);
}
}
}
Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of the
original condition in consideration.
Example:
using System;
namespace Logical
{
class Prog
{
static void Main()
{
bool a = true, b = false, result;
result = a && b;
Console.WriteLine("AND Operator: " + result);
result = a || b;
Console.WriteLine("OR Operator: " + result);
result = !a;
Console.WriteLine("NOT Operator: " + result);
}
}
}
Assignment Operators:
Assignment operators are used to assigning a value to a variable.
Example:
using System;
namespace OperatorsAppl
{
class Prog
{
static void Main() {
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - Value of c = ", c);
c += a;
Console.WriteLine("Line 2 - Value of c = ", c);
c -= a;
Console.WriteLine("Line 3 - Value of c = ", c);
c *= a;
Console.WriteLine("Line 4 - Value of c = ", c);
c /= a;
Console.WriteLine("Line 5 - Value of c = ", c);
}
}}
23
Bitwise Operator:
In C#, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations.
Example:
using System;
namespace OperatorsAppl {
class Program
{
static void Main() {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c ;
c = a & b;
Console.WriteLine("Line 1 - Value of c is ", c );
c = a | b;
Console.WriteLine("Line 2 - Value of c is ", c);
c = a ^ b;
Console.WriteLine("Line 3 - Value of c is ", c);
}
}
}
Miscellaneous/Special Operators:
Example:
using System;
namespace OperatorsAppl {
class Program {
static void Main(string[] args) {
/* example of sizeof operator */
Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of double is {0}", sizeof(double));
24
/* example of ternary operator */
int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}
Type Conversion
Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#,
type casting has two forms −
Implicit type conversion − In implicit type conversion, the C# compiler automatically converts one
type to another. Generally, smaller types like int (having less memory size) are automatically converted
to larger types like double (having larger memory size).
char -> int -> long -> float -> double
Explicit type conversion − In explicit type conversion, we explicitly convert one type to another.
Generally, larger types like double (having large memory size) are converted to smaller types like int
(having small memory size).
double -> float -> long -> int -> char
Console.WriteLine(myInt);
Console.WriteLine(myDouble);
}
}
}
Example for Explicit:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble);
25
Console.WriteLine(myInt);
}
}
}
Control Structures in C#
The control statements are used to control the flow of execution of the program.
Selection statements: Selection statements control program flow through the result of evaluating
boolean (true and false) values.
if, if-else, else-if, switch.
Iteration/looping statements: In the program, you perform some task or repeat some task on the
basis of iteration. Whenever the condition is true, the program knows to repeat. Once that condition is
false, then it’s time to stop repeating.
for , while, do while , foreach
Jump statements: Jumping statements are control statements that transfer execution control from one
point to another point in the program.
break , continue .
Selection statements
if condition
The if statement checks the given condition. If the condition evaluates to be true then the block of
code/statements will execute otherwise not.
Syntax
if(condition)
{
statement;// it must be true
}
An example
using System;
namespace MyApplication{
class demo{
int a=20,b=10;
static void Main()
{
if (a>b)
{
Console.WriteLine("a is greater than b");
}
26
}
}
}
If-else statement : The C# if-else statement also tests the condition. It executes the if block if condition
is true otherwise else block is executed.
Syntax
if(condition)
{
statement;//executes if condition is true
}
else
{
statement;// executes if condition is false
}
Example
using System;
namespace MyApplication{
class demo{
int a=20,b=10;
static void Main()
{
if (a>b)
{
Console.WriteLine("a is greater than b"); }
else {
Console.WriteLine("b is greater than a");
}
}
}
}
Else-if: If we have to specify two conditions which are related to each other, we can use the else if
statement to specify the second condition and its related code block.
Syntax
if(condition1)
{
statement;
}
else if(condition2)
{
statement;
}
else(condition3)
{
statement;
}
Example
using System;
namespace MyApplication{
class demo{
int a=20,b=10;
static void Main()
{
27
if (a>b)
{
Console.WriteLine("a is greater than b"); }
else if (b>a){
Console.WriteLine("b is greater than a");}
else {
Console.WriteLine("Both are equal");
}
}
}
}
Switch statement: The switch expression is evaluated once. The value of the expression is compared
with the values of each case. If there is a match, the associated block of code is executed.
Syntax
switch (expression)
{
case: 1
statement;
break;
case: 2
statement;
break;
.
.
default;
statement;
}
Example
using System;
namespace MyApplication{
class demo {
static void Main()
{
int year = 2;
switch (year)
{
case 1:
Console.WriteLine("2021");
break;
case 2:
Console.WriteLine("2022");
//it will output this we have switched it.
break;
case 3:
Console.WriteLine("2023");
break;
}
}
}
28
Iteration statements:
For loop : C# for loop is used to repeat a set of statements until a given condition is evaluated to False.
It is useful where you know in advance how many times program should iterate.
Syntax:
for(initialization; condition; increment/decrement)
{
statement;
}
Example:
using System;
class ForExample
{
static void Main()
{
for(int i=0;i<10;i++){
Console.WriteLine (i);
}
}
}
While loop: It is a simple loop. It executes till the code block while the condition is true. If the condition is
going to be false, the program will exit from the loop.
Syntax:
while(condition)
statement;
Example:
using System;
class WhileExample
{
static void Main()
{
int i=0;
while(i<10)
{
Console.WriteLine(i);
i++;
}
}
}
do while statement: This loop will execute the code block once, before checking if the condition is true,
then it will repeat the loop as long as the condition is true.
Syntax:
do
{
statement;
}
while (condition)
Example:
using System;
class DoWhileExample
{
static void Main()
29
{
int i = 1;
do{
Console.WriteLine(i);
i++;
}
while (i <= 10) ;
}
}
Foreach statement: The foreach loop is used to iterate over the elements of the collection. The
collection may be an array or a list. It executes for each element present in the array.
Syntax:
foreach(data_type var_name in
collection_variable)
{
// statements to be executed
}
Example:
using System;
class foreachExample
{
static void Main()
{
int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };
foreach(int items in a_array)
{
Console.WriteLine(items);
}
}
}
Jump statements:
The break statement is used when one needs the code to terminate some statement and perhaps go to
the next.
Continue statements: These kinds of statements are mostly used when a programmer wants the
program to skip a certain part of an execution, for example in loop statements.
Example:
using System;
class demo{
static void Main()// Main Method
{
for (int i = 0; i< 7; i++)
{
if (i== 4)
continue;
Console.WriteLine(j);
}
}
}
30
Methods in C#
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also
known as functions.
To use a method, you need to −
o Define the method
o Call the method
Declaration of method:
Syntax:
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
Method Invocation:
Method Invocation or Method Calling is done when the user wants to execute the method. The method
needs to be called for using its functionality. A method returns to the code that invoked it when:
o It completes all the statements in the method
o It reaches a return statement
o Throws an exception
Example:
static int Sum(int x, int y)
{
int a = x;
int b = y;
int result = a + b;
return result;
}
static void Main(string[] args)
{
int a = 12;
int b = 23;
int c = Sum(a, b);
Console.WriteLine("The Value of the sum is " + c);
}
}
}
Method parameters
Information can be passed to methods as parameter. Parameters act as variables inside the method.
They are specified after the method name, inside the parentheses. You can add as many parameters
as you want, just separate them with a comma.
Types of parameters
Value parameter
Reference parameter
Output parameter
Parameter arrays
31
Value parameter
In value type parameter, the actual value gets passed to the function. Passing a value type
variable as parameter means, you are passing the copy of the value.Value parameters are the
parameters that are passed by value.
Example program
using System;
class program{
static void Cube(int x)
{
x = x * x * x;
Console.WriteLine("Value Within the Cube method : {0}", x);
}
static void Main()
{
int num = 5;
Cube(num);
Console.WriteLine( num);
Console.ReadKey();
}
}
Reference parameter
Reference Type: A Reference type variable contains memory address of value.
The ref is a keyword in C# which is used for passing the value types by reference. Or we can
say that if any changes made in this argument in the method will reflect in that variable
when the control return to the calling method.
Example program
using System;
class Program
{
static void Main(string[] args)
{
int val;
val = 4;
Console.WriteLine("Value Before :", val);
square(ref val);
Console.WriteLine("Value After : ", val);
}
static void square(ref int refParam) {
refParam *= refParam;
}
}
Output parameter
A return statement can be used for returning only one value from a function. However, using
output parameters, you can return two values from a method. C# out parameter is used when a
method returns multiple values.
When a parameter passes with the Out keyword/parameter in the method, then that method
works with the same variable value that is passed in the method call. If variable value changes,
the method parameter value also changes.
32
Example:
using System;
class program
{
static void arithmetic (int a, int b, out int s, out int p)
{
s=a+b;
p=a*b;
}
static void main( )
{
int a=10, b=20, sum, prod;
arithmetic (a,b, out sum, out prod);
}
}
Example:
using System;
class parameterArrays
{
static void parray (params int[ ] a)
{
foreach ( int i in a)
Console. writeLine(i);
}
State void Main( )
{
int[ ] a={11,22,33};
parray(a);
parray( );
parray(10,20);
}
}
Nesting of methods
A method can be called by using only its name by another method of the same class. This is
known as nesting of methods.
A nested method is a method that is defined inside another method. A nested method is also
called a local method or a local function.
Example program
using System;
class Program
int a,b;
33
void getvalue()
{
a=4;
b=10;
}
Void show()
{
getvalue();
if(a>b)
{
Console.WriteLine(“A is greater value”);
}
else
{
Console.WriteLine(“B is greater value”);
}
}
static void main()
{
Program obj=new Program();
obj.show();
}
}
}
Method Overloading
Having two or more methods with same name but different in parameters, is known as
method overloading in C#. Method Overloading is the common way of implementing
polymorphism.
Method overloading is used when methods are required to perform similar tasks but using
different input parameters. Instead of defining two methods that should do the same thing,
it is better to overload .
Example program
using System;
namespace MethodOverload {
class Program {
34
Arrays in C#
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together.
The base index of array starts with 0 and ends with n-1.
To access or retrieve index is used.
Declaration of Array
To declare an array in C# place a pair of square brackets after the variable type. The syntax is given
below :
type[] arrayname;
For Example:
int[] a;
float[] marks;
double[] x;
int[] m, n;
Memory allocation for arrays
After declaring an array, we need to allocate space by defining the size of array.
Syntax: arrayname = new type[size];
Example: a = new int[5];
marks = new float[6];
x = new double[10];
It is also possible to combine the two steps, declaration and memory allocation of array, into one as
shown below:
Example: int[] num = new int [5];
Initialization of array
This step involves placing data into the array. Arrays are automatically assigned the default
values associated with their type.
The initialization process is done using the array subscripts as shown:
Syntax: arrayname[subscript] = value;
Example:
num[0] = 5;
num[1] = 15;
num[2] = 52;
num[3] = 45;
We can also initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below:
Syntax: type[] arrayname = { list of values };
Example: int[] num = {5,15,52,45};
Types of Arrays
Single Dimensional Array: A One-Dimensional Array is the simplest form of an Array in which
the elements are stored linearly and can be accessed individually by specifying the index value
of each element stored in the array. A single pair of the square bracket is used to represent a
single row (hence 1-D) of values under a single name.
35
Example Program:
using System;
class ArrayProg {
public static void Main()
{
int[] arr = { 20, 30, 40, 50, 60 };
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine( arr[i] );
}
}
}
Multidimensional Array: It is also called rectangular arrays, A multidimensional array is an
array with more than two dimensions. In a matrix, the two dimensions are represented by rows
and columns. Each element is defined by two subscripts, the row index and the column index.
Creating a Multi-dimensional array
Syntax: int[,] arr = new int[3, 3]; //2d array
int[,,] arr= new int[3, 3, 3]; //3d array
Example Program:
using System;
class Multi_ArrayProg
{
public static void Main()
{
int[,] arr = new int[3, 3]; //initialization 3 rows and 3 columns
arr[0,1]=10;
arr[1,2]=20;
arr[2,0]=30;
int i, j;
for( i=0; i<3; i++){
for( j=0; j < 3; j++) {
Console.WriteLine ( arr[i, j] );
}
}
}
}
Jagged Array:
These types of arrays are mainly called "array of arrays". A jagged array is an array whose
elements are arrays, possibly of different sizes. The element size differs in the case of jagged
arrays.
Syntax: int[][] arr = new int[2][];
arr[0] = new int[4];
arr[1] =new int[6];
Example Program:
using System;
class JaggedArrayProg
{
public static void Main()
{
int[][] arr= new int[2][];
arr[0] = new int[] { 62, 24, 9, 37 };
arr[1] = new int[] { 43, 42, 68, 80, 15, 73 };
36
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
Console.WriteLine( arr[i][j] + " " );
}
}
}
}
Array Class
Strings
Strings are used for storing text.
A string variable contains a collection of characters surrounded by double quotes
Syntax: string greeting = "Hello”;
Example:
using System;
class StrProg
37
{
static void Main(){
string greeting = "Hello";
Console.WriteLine(greeting);
}
}
Types of strings
The immutable strings are those which can‘t be modified once objects are created and mutable
strings are modifiable. C# also supports a feature of regular expression that can be used for
complex strings manipulations and pattern matching
Immutable strings
Once object created it is immutable (can’t change).Immutable strings are created using string
object.
Example program for immutable strings
using System:
namespace Prog
{
Class P1
[
static void main()
{
string userstring=”C#”;
userstring+=”Programming”;
userstring+=”language”;
Console.WriteLine(userstring);
}
}
}
38
Inserting String
string s1 =" Wel";
string s1.insert(3,"come")
Comparing Strings
string. Compare(s1,s2);
bool a = s2.Equals(s1);
bool b = string.Equal(s1,s2);
if(s1==s2)
Console.WriteLine(“both are equal”);
Mutable String
Mutable strings are those strings, which can be modify dynamically. This type of strings are
created using StringBuilder class.
It does not create unnessasary string objects
For Example:
StringBuilder s1 = new StringBuilder(“Welcome”);
StringBuilder s2 = new StringBuilder( );
The StringBuilder class supports many methods that are useful for manipulating dynamic
strings. Some of the most common methods are listed below
39
Example:
using System.Text; //For using StringBuilder
using System;
class StrMethod
{
public static void Main( )
{
StringBuilder s = new StringBuilder("C");
Console.WriteLine(" Stored String is :"+ s);
Console.WriteLine("Length of string is :"+s.Length);
s.Append("Sharp ");
Console.WriteLine( "After Append String is :"+ s);
Console.WriteLine("Length of string is :"+s.Length);
s.Insert(7,"Language");
Console.WriteLine("After Insertion String is:"+ s);
Console.WriteLine("Length of string is :"+s.Length);
int n = s.Length;
s[n] = "!";
Console.WriteLine(" At Last String is :"+ s);
}
}
OUTPUT:
Stored String is : C
Length of String is : 1
After Append string is : CSharp
After Insertion String is : CSharp Language
At Last String is : CSharp Language!
40
Regular Expression
In C#, Regular Expression is used for the parsing and validation of the given text to match with the
defined pattern (for example, an email address). The pattern can contain operators, characters literals,
or constructs.
Regex Class
Regex class shows the regular expression engine in the .NET Framework. Regex class is used to parse a
large amount of text for finding the specific character pattern. We can use the Regex class for the
extraction, editing, for the replacement, or to delete the text of the substring.
Example: // Create a pattern for the word that starts with letter "M"
string pattern = @"\b[M]\w+";
// Create a Regex
Regex rgex = new Regex (pattern);
System.Text.RegularExpressions namespace contains the Regex class.
Program:
using System;
using System.Text; //for StringBuilder class
using System.Text.RegularExpressions; //for Regex class
Program:
Class RegexTest
{
public static void Main()
{
string str;
str = "Amar, Akbar, Antony are friends!";
Regex reg = new Regex ("|, "); StringBuilder sb = new StringBuilder();
int count = 1;
41
Program for Structure
using System;
namespace ConsoleApplication {
// Defining structure
public struct Person
{
public string Name;
public int Age;
}
class StruExample
{
static void Main()
{
Person P1; // Declare P1 of type Person
P1.Name = "Keshav Gupta";
P1.Age = 21;
Console.WriteLine(“Name:”+P1.Name);
Console.WriteLine(“Age:”+P1.Age);
}
}
}
In the above code, a structure with name “Person” is created with data members Name, Age in the main
method, P1 of structure type Person is created. Now, P1 can access its data members with the help of .(
dot ) Operator.
Copying Structure
Copy Structure: In C#, user can copy one structure object into another one using ‘=’ (Assignment)
operator
Syntax: Structure_object_destination = structure_object_source;
P2=P1
Example Program: (Refer above Example)
using System;
namespace ConsoleApplication {
// Defining structure
public struct Person
{
public string Name;
public int Age;
}
class StruExample
{
static void Main()
{
Person P1; // Declare P1 of type Person
P1.Name = "Keshav Gupta";
P1.Age = 21;
Person P2
P2=P1
Console.WriteLine(“Name:”+P1.Name);
Console.WriteLine(“Age:”+P1.Age);
}
}
}
42
Person P2;
// Copying the values of P1 into P2
P2 = P1;
Console.WriteLine("Name: " +P2.Name);
Console.WriteLine("Age: " +P2.Age);
Nesting Structure
C# allows the declaration of one structure into another structure and this concept is termed as the
nesting of the structure.
public struct Address
{
// data member of Address structure
public string City;
public string State;
}
// Another structure
struct Person
{
// data member of Person structure
public string Name;
public int Age;
}
Example Program:
using System;
namespace ConsoleApplication
{
public struct Address
{
public string City;
public string State;
}
struct Person
{
public string Name;
public int Age;
public Address A1;
}
class StrcExample {
static void Main()
{
Person p1;
p1.Name = "aaaa";
p1.Age = 12;
p1.A1.City = "Mysuru_City";
p1.A1.State = “Karnataka State";
Console.WriteLine("Name: " +p1.Name);
Console.WriteLine("Age: " +p1.Age);
Console.WriteLine("City: " +p1.A1.City);
Console.WriteLine("State: " +p1.A1.State);
}
43
}
}
struct Number
{
int number; //data member
public Number(int value) //constructor
{
Number=value;
}
}
Struct vs Classes
Structure Class
Value Type Reference type
Copies the value Copies the reference
Parameterless Constructors not Allowed Allowed
Inheritance not supported Always supported
Enumerations
An enumeration is a set of named integer constants. An enumerated type is declared using the enum
keyword. C# enumerations are value data type. In other words, enumeration contains its own values
and cannot inherit or cannot pass inheritance. It is used to store a set of named constants such as
season, days, month, size etc. The enum constants are also known as enumerators
Declaring enum Variable
Syntax:
enum <enum_name>
{
enumeration list
};
Example Program:
using System;
namespace EnumApplication {
44
class EnumProgram {
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: ", WeekdayStart);
Console.WriteLine("Friday: ", WeekdayEnd);
OUTPUT:
Console.ReadKey(); Monday:1
} Friday:5
}
}
{
Console.WriteLine(WeekDays.Friday);
int day = (int) WeekDays.Friday;
Console.WriteLine(day);
var wd = (WeekDays)5;
Console.WriteLine(wd);
}
}
45
UNIT-2
OOPS With C#
Classes, Objects, Inheritance, Polymorphism, Interfaces, Operator Overloading Delegates,
Events, Errors and Exceptions.
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class
combines the fields and methods (member function which defines actions) into a single unit. In C#,
classes support polymorphism, inheritance and also provide the concept of derived classes and base
classes. It can have fields, methods, constructors etc.
Declaration of Classes
Class is an user-defined data type. To create a class, you start with the class keyword followed
by a name and its body delimited by curly brackets.
Syntax:
class classname
{
// class-body
}
The class-body contains the member data and member function of the class.
Members of Class
Class is a mechanism to implement the encapsulation, it bind the data and a function in a
single unit. Therefore data and functions are the members of class, which is known as member
data and member function.
Example of full class :
class Circle
{
double radius;
public void get_radius(double r)
{
radius = r;
}
public double area()
{
return ( 3.14 * r *r);
}
}
Member Access Modifiers/visibility control:
Access modifiers provide the accessibility control for the members of classes to outside the
class. They also provide the concept of data hiding. There are five member access modifiers
provided by the C# Language. By default all member of class have private accessibility.
46
Example:
class Demo
{
public int a;
internal int x;
protected double d;
float m; // private by default
}
Objects
Object is an instance of a class. All the members of the class can be accessed through objects. In
C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behaviour. Here, state means data and
behaviour means functionality.
Object is a runtime entity, it is created at runtime.
Example:
Student s1 = new Student();//creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class. The new keyword allocates memory at runtime.
C# Constructor
In C#, constructor is a special method which is invoked automatically at the time of object creation. It is
used to initialize the data members of new object generally. The constructor in C# has the same name as
class name.
A constructor cannot be abstract, final, and Synchronized.
A constructor doesn’t have any return type, not even void
Syntax:
class Car {
// constructor
Car()
{
//code
}
}
Once we create a constructor, we can call it using the new keyword.
new Car();
Default constructor
47
A constructor which has no argument or constructor without any parameters is called a default
constructor. It is invoked at the time of creating object.
The drawback of a default constructor is that every instance of the class will be initialized to the
same values and it is not possible to initialize each instance of the class to different values.
Example:
using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
}
}
Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different
values to distinct objects. . It can initialize each instance of the class to different values.
Example:
using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int i, String n,float s)
{
id = i;
name = n;
salary = s;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sonoo", 890000.00);
Employee e2 = new Employee(102, "Mahesh", 490000.00);
e1.display();
e2.display();
}
}
Static constructor
C# static constructor is used to initialize static fields. It can also be used to perform any action that is to
be performed only once. It is invoked automatically before first instance is created or any static member
is referenced.
C# static constructor cannot have any modifier or parameter.
C# static constructor is invoked implicitly. It can't be called explicitly.
Example:
48
using System;
class Account
{
public int id;
public String name;
public static float Interest;
public Account(int i, String n)
{
id = i;
name = n;
}
static Account()
{
Interest = 9.5;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+Interest);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Account a1 = new Account(101, "Sonoo");
Account a2 = new Account(102, "Mahesh");
a1.display();
a2.display();
}
}
Destructor
A destructor works opposite to constructor, It destructs the objects of classes. It can be defined only
once in a class. Like constructors, it is invoked automatically. ~ Symbol is used to destruct the objects.
Example:
public class Employee
{
public Employee()
{
Console.WriteLine("Constructor Invoked");
}
~Employee()
{
Console.WriteLine("Destructor Invoked");
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee();
}
}
Constructor Overloading
49
Constructor Overloading is a technique to define multiple constructors within a class with different sets
of parameters to achieve polymorphism. We can overload constructors in C# just like methods. We can
do so by changing the signatures by using a different number, or type of parameters.
Syntax:
class Car {
Car(string brand) {
...
}
Car(int price) {
...
}
}
Example:
using System;
namespace ConstructorOverload {
class Car {
Car(string brand) // constructor with string parameter
{
Console.WriteLine("Brand: " + brand);
}
Car(int price) { // constructor with int parameter
Console.WriteLine("Price: " + price);
}
static void Main(string[] args)
{
Car car = new Car("Lamborghini");
Console.WriteLine();
Car car2 =new Car(50000);
}
}
Indexers in C#
An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this
class behaves similar to array. You can then access the instance of this class using the array access
operator ([ ]).
Syntax
A one dimensional indexer has the following syntax −
element-type this[int index] {
get {
// body
}
set {
//body
}
}
Example Program
using System;
class Test
{
string[] names=new string[4];
public string this[int i]
50
{
get
{
return names[i];
}
set{
names[i]=value;
}
static void Main()
Test obj=new Test();
obj[0]=”car”;
obj[1]=”omni”;
obj[2]=”scooty”;
for(int i=0;i<3;i++)
Console.WriteLine(obj[i]);
}
}
Overloaded Indexers:
Indexers can be overloaded. Indexers can also be declared with multiple parameters and each
parameter may be a different type. It is not necessary that the indexers have to be integers. C# allows
indexes to be of other types.
Example:
public string this[int i]
{
get
{
return names[i];
}
set{
names[i]=value;
}
public string this[double i]
{
get
{
return names[i];
}
set{
names[i]=value;
}
Inheritance
In C#, inheritance is a process in which one object acquires all the properties and behaviours of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviours
which is defined in other class. Code reusability: Now you can reuse the members of your parent class.
So, there is no need to define the member again. So less code is required in the class.
Derived Class (child) - the class that inherits from another class
Base Class (parent) - the class being inherited from.
Syntax:
class derived-class : base-class
{
// methods and fields
.
.
51
}
Types of Inheritance in C#
Single Inheritance: In single inheritance, subclasses inherit the features of one superclass. In image
below, the class A serves as a base class for the derived class B.
Syntax:
class sub_class_name : base_class_name
{
//body of subclass
};
Example Program:
using System;
namespace InheritanceEg
{
public class ParentClass
{
public void printParent()
{
Console.WriteLine("This is Parent Class");
}
}
Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a base class and as
well as the derived class also act as the base class to other class. In below image, class A serves as a base
class for the derived class B, which in turn serves as a base class for the derived class C.
52
Example Program:
using System;
namespace InheritanceEg
{
public class Animal
{
public void sleep()
{
Console.WriteLine("Animal sleeps");
}
}
p.sleep();
p.sound();
p.weep();
}
}
}
Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass. In below image, class A serves as a base class for the derived class B, C, and D.
Syntax:
class One
53
{
// Class One members
}
class Two : One
{
// Class Two members.
}
class Three : One
{
// Class Three members
}
Example Program:
using System;
namespace InheritanceEg
{
public class ParentClass
{
public void printParent()
{
Console.WriteLine("This is Parent Class");
}
}
54
s.printSon();
s.printParent();
d.printDaughter();
d.printParent();
}
}
}
Multiple Inheritance(Through Interfaces):In Multiple inheritance, one class can have more than one
superclass and inherit features from all parent classes. Please note that C# does not support multiple
inheritance with classes. In C#, we can achieve multiple inheritance only through Interfaces.
Example Program:
using System;
namespace InheritanceEg
{
interface Dog
{
void dogFunc();
}
interface Cat
{
void catFunc();
}
public class Animal: Dog, Cat //Inheriting Dog and Cat interface
{
public void dogFunc()
{
Console.WriteLine("I am a Dog");
}
55
public class Program
{
public static void Main(string[] args)
{
Animal obj = new Animal();
obj.animalFunc();
obj.dogFunc();
obj.catFunc();
}
}
}
Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of inheritance.
Since C# doesn’t support multiple inheritance with classes, the hybrid inheritance is also not possible
with classes. In C#, we can achieve hybrid inheritance only through Interfaces.
Abstract Classes
An abstract class can have both abstract methods (method without body) and non-abstract
methods (method with the body).
As we cannot create objects of an abstract class, we must create a derived class from it. So that
we can access members of the abstract class using the object of the derived class.
The abstract is a modifier and when used to declare a class indicates that class cannot be
instantiated. Only derived class can be instantiated.
Example:
abstract class Base
{
…….
}
class Derived: Base
{
…….
}
Derived d1
Abstract Methods
A method that does not have a body is known as an abstract method. We use the abstract
keyword to create abstract methods.
Example:
o public abstract void Draw(int x, int y)
56
Its implementation is provided by derived classes by overriding the method.
Example:
sealed class Aclass
{
………
}
sealed class Bclass: Aclass
{
………..
}
Any attempt to inherit these classes will cause an error and the compiler will not allow it.
Sealed Methods
o The method is said to be sealed if a derived class cannot override this method,
o A sealed method is used to override and inherited virtual method with the same signatures.
Example: The sealed method Fun()overrides the virtual method Fun()defined in class A. Any
derived class cannot further override the method Fun().
class A
{
public virtual void Fun()
{
……..
}
}
class B:A
{
public sealed override void Fun()
{
…….
}
}
Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms.
Polymorphism provides the ability to a class to have multiple implementations with the same name.
57
Compile time polymorphism is achieved by method overloading and operator overloading in C#. It
is also known as static binding or early binding. Runtime polymorphism in achieved by method
overriding which is also known as dynamic binding or late binding.
Method Overriding
If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific
implementation of the method which is already provided by its base class.
In simple words, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes.
To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.
Example:
using System;
class Base
{
public virtual void display()
{
Console.WriteLine(“Base class display:”);
}
public override void display ()
{
Console.WriteLine(“Derived class display:”);
}
class Derived: Base
{
static void Main()
{
Derived obj=new Derived();
obj. display();
}
}
}
Method Hiding
C# also provides a concept to hide the methods of the base class from derived class, this concept is
known as Method Hiding. It is also known as Method Shadowing. In method hiding, you can hide the
implementation of the methods of a base class from the derived class using the new keyword.
58
class Base
{
public void display()
{
Console.WriteLine(“Base class display:”);
}
public new void display ()
{
Console.WriteLine(“Derived class display:”);
}
class Derived: Base
{
static void Main()
{
Derived obj=new Derived();
obj. display();
}
}
}
C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated. But interfaces will contain only the declaration of the members. The implementation of the
interface’s members will be given by class who implements the interface implicitly or explicitly.
Multiple inheritance is possible with the help of Interfaces but not with classes
Interfaces specify what a class must do and not how.
Syntax
interface <interface_name >
{
// declare methods
}
Multiple Interface
C# allows the implementation of multiple interfaces with the same method name. To understand how to
implement multiple interfaces with the same method name.
Syntax:
class Rectangle : Polygon, Color
{
public void calArea(int a, int b)
{
………………
}
using System;
interface Polygon {
void calArea(int a, int b);
}
59
interface Color //another interface
{
void getColor();
}
// implements two interface
class Rectangle : Polygon, Color
{
public void calArea(int a, int b)
{
int area = a * b;
Console.WriteLine("Area of Rectangle: " + area);
}
public void getColor()
{
Console.WriteLine("Red Rectangle");
}
}
class Program {
static void Main (string [] args) {
Rectangle r1 = new Rectangle();
r1.calculateArea(100, 200);
r1.getColor();
}
}
}
Nested Classes in C#
A class is a user-defined blueprint or prototype from which objects are created. C#, a user is
allowed to define a class within another class. Such types of classes are known as nested class.
This feature enables the user to logically group classes that are only used in one place, thus this
increases the use of encapsulation, and create more readable and maintainable code.
Syntax:
class Outer_class
{
// Code..
class Inner_class
{
// Code..
}
}
Operator Overloading
Operator overloading gives the ability to use the same operator to do various operations. It provides
additional capabilities to C# operators when they are applied to user-defined data types. An operator
can be overloaded by defining a function to it. The function of the operator is declared by using the
operator keyword.
An operator can be overloaded by defining a function to it. The function of the operator is declared by
using the operator keyword.
Syntax:
access specifier className operator Operator_symbol (parameters)
{
// Code
60
}
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.
61
num3.display(); // Displays 240
}
}
Delegates in C#
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that
holds the reference to a method.it is a type that represents references to methods with a particular
parameter list and return type and then calls the method in a program for execution when it is needed.
Delegates are especially used for implementing events and the call-back methods.
It provides a good way to encapsulate the methods.
These are the type-safe pointer of any method.
All delegates are implicitly derived from the System.Delegate class.
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the new keyword and
be associated with a particular method.
The parameters passed to the delegate by the caller are passed to the method, and the return
value, if any, from the method, is returned to the caller by the delegate. This is known as
invoking the delegate.
Syntax:
[delegate_name] [instance_name] = new [delegate_name](calling_method_name);
62
Console.WriteLine("After c1 delegate, Number is: " + getNumber());
c2(3);
Console.WriteLine("After c2 delegate, Number is: " + getNumber());
}
}
Multicasting Delegates
A delegate that holds a reference to more than one method is called multicasting delegate.
Multicast Delegates are also known as Combinable Delegates,
The delegate can point to multiple methods. A delegate that points multiple methods is called a
multicast delegate. The "+" or "+=" operator adds a function to the invocation list, and the "-" and "-="
operator removes it.
Example:[Refer same above example program of delegates]
Events in C#
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as
system generated notifications. Applications need to respond to events when they occur.
The events are declared and raised in a class and associated with the event handlers using delegates
within the same class or some other class. The class containing the event is used to publish the event.
This is called the publisher class. Some other class that accepts this event is called the subscriber class.
Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The event-
delegate association is also defined in this object. A publisher class object invokes the event and
it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in
the publisher class invokes the method (event handler) of the subscriber class.
63
bl.StartProcess();
}
Errors
Errors refer to the mistake or faults which occur during program development or execution. If you don't
find them and correct them, they cause a program to produce wrong results.
Errors may be broadly classified into two categories:
Compile time errors
Runtime errors
Compile-time errors are the errors that occurred when we write the wrong syntax.
Most common Compile time errors are:
Missing semicolons.
Missing brackets in classes and methods.
Misspelling of identifiers and keywords.
Missing double quotes.
Use of undeclared variables.
Runtime-time errors are sometimes program may successfully compile but not run properly. Such
program may produce wrong results due to wrong logic or may terminate due to errors.
Most common Runtime-errors are:
Dividing an integer by zero.
Accessing an element that is out of the bounds of an array.
Trying to store a value into an array of an incompatible class or type.
Attempting to use negative size for an array.
Converting invalid string to number vice versa.
Exceptions in C#
An exception is a problem that arises during the execution of a program. A C# exception is a response to
an exceptional circumstance that arises while a program is running, such as an attempt to divide by
zero.
Exception Handling Mechanisms:
Exceptions provide a way to transfer control from one part of a program to another. C# exception
handling is built upon four keywords: try, catch, finally, and throw.
64
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by
one or more catch blocks.
catch − A program catches an exception with an exception handler at the place in a program where you
want to handle the problem. The catch keyword indicates the catching of an exception.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown
or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword
Syntax:
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: ", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
65
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly
derived from the System.Exception class.
Some of the exception classes derived from the System.Exception class are the
System.ApplicationException and System.SystemException classes.
The System.SystemException class is the base class for all predefined system exception.
Exception Class & Description
o
System.IO.IOException
Handles I/O errors.
System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
System.NullReferenceException
Handles errors generated from referencing a null object.
System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.
System.InvalidCastException
Handles errors generated during typecasting.
System.OutOfMemoryException
Handles errors generated from insufficient free memory.
System.StackOverflowException
Handles errors generated from stack overflow.
Exception hierarchy
The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of
the Object class. Throwable has two direct subclasses - Exception and Error. The Exception class is used
for exception conditions that the application may need to handle.
66
Throwing Objects/Exceptions
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You
can use a throw statement in the catch block to throw the present object as −
Catch(Exception e) {
...
Throw e
}
67
Program obj = new Program();
double num = 9, den = 0, quotient
try
{
quotient = obj.DivisionOperation(num, den);
Console.WriteLine("Quotient = {0}", quotient);
}
catch (Exception e) {
Console.Write(e.Message);
}
}
}
68
{
Console.WriteLine(e);}
If we want to uncheck
int a=2000000
int b=3000000
try
{
int n=unchecked(a*b)
}
catch (OverflowException e)
{
Console.WriteLine(e);}
Multithreading
C# Multithreading
Multithreading in C# is a process in which multiple threads work simultaneously. It is a process to
achieve multitasking. It saves time because multiple tasks are being executed at a time. To create
multithreaded application in C#, we need to use System.Threading namespace.
Threads are lightweight processes. One common example of use of thread is implementation of
concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and
increase efficiency of an application.
The Unstarted State − It is the situation when the instance of the thread is created but the Start method
is not called.
The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle.
The Not Runnable State − A thread is not executable, when
The Dead State − It is the situation when the thread completes execution or is aborted.
Introduction to VB.NET
.NET Framework
69
The .NET Framework class library facilitates types (CTS) that are common to all
.NET languages.
NET Framework Architecture has languages at the top such as VB .NET C#, VJ#,
VC++ .NET; developers can develop (using any of above languages) applications
such as Windows Forms, Web Form, Windows Services and XML Web Services.
Bottom two layers consist of .NET Framework class library and Common Language
Runtime.
VB.NET Introduction
1. VB.NET is a simple, multi-paradigm object-oriented programming language designed to create a
wide range of Windows, Web, and mobile applications built on the .NET Framework.
2. The VB.NET stands for Visual Basic. Network Enabled Technologies. It is a simple, high-level,
object-oriented programming language developed by Microsoft in 2002.
3. Furthermore, it supports the OOPs concept, such as abstraction, encapsulation, inheritance, and
polymorphism. It is not a case sensitive language, whereas, C++, Java, and C# are case sensitive
language.
Features of VB.NET
70
It supports a rapid application development tool kit. In which a developer does not need to
write all the codes as it can get various code automatically from its libraries. For example, when
we create a form in Visual basic.net, it automatically calls events of various form in that class.
It is not a case sensitive language like other languages such as C++, java, etc.
It supports Boolean condition for decision making in programming.
It also supports the multithreading concept, in which you can do multiple tasks at the same time.
It provides simple events management in .NET application.
A Window Form enables us to inherit all existing functionality of form that can be used to create
a new form. So, in this way, it reduced the code complexity.
It uses an external object as a reference that can be used in a VB.NET application.
Automatic initialized a garbage collection.
It follows a structured and extensible programming language for error detection and recovery.
Conditional compilation and easy to use generic classes.
It is useful to develop web, window, and mobile applications.
Module Module1
'This program will display Hello World
Sub Main() //MAIN METHOD
Console.WriteLine("Hello World") //DISPLAYS OUTPUT
Console.ReadKey()
End Sub //stops
End Module
The First line has a Module declaration, the module Module1. VB.Net is completely object
oriented, so every program must contain a module of a class that contains the data and
procedures that your program uses.
The next line defines the Main procedure, which is the entry point for all VB.Net programs. The
Main procedure states what the module or class will do when executed.
The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from
running and closing quickly when the program is launched from Visual Studio .NET.
IDE is a term commonly used in the programming world to describe the interface and environment that
we use to create our applications. It is called integrated, because we canaccess virtually all of the
development tools that we need from one screen, called aninterface
71
●Properties Window
●Form Designer
●Form Layout
●Solution Explorer
Click the Windows key, and then browse to the Office program for
which you want to create a desktop shortcut.
Right-click the program name or tile, and then select Open file location.
Right-click the program name, and then click Send To > Desktop (Create shortcut).
72
Adding buttons to toolbar and setting icons to buttons
Now let's create a sample. We are going to add three Button controls, three separators and a
Label control.
Now next we are going to set an icon for the Button controls by setting Image property of
Button.
Once you click on the browse option to browse an image, Resource editor window pops up
where you can import an image. Click on Import button and browse an image file.
We set three icons for all three buttons and the ToolStrip.
Program
Public Class Form1
Private Sub toolStripButton1_Click(sender As System.Object, e As System.EventArgs)
ToolStripLabel1.Text = "Debug is clicked"
End Sub
Private Sub ToolStripButton2_Click(sender As System.Object, e As
System.EventArgs)
ToolStripLabel1.Text = "delete is clicked"
End Sub
Private Sub ToolStripButton3_Click(sender As System.Object, e As
System.EventArgs)
ToolStripLabel1.Text = "save is clicked"
End Sub
End Class
73
If push pin is vertical then
autohide is activated
ToolBox
Tool Box consists of all the controls essential for developing a VBapplication. Controls are elements that
provide the user interface. Controls are tools such as text box, command button, label and other objects
that can be dragged and drawn on a form to perform certain tasks according to the events associated.
74
The Dock property of the Control class does this. The Dock property gets or sets which control borders
are docked to its parent control and determines how a control is resized with its parent.
Use the Visual Studio designer Properties window to set the docking mode of a control.
Docking in code
Set the Dock property on a control. In this below code, a button is docked to the right side of its
container:
button1.Dock = DockStyle.Right;
DockPadding-The container (form, panel, or other type of container control) has a DockPadding
property, which allows it to specify a certain amount of padding between it and
docked controls. The padding values can be specified individually for the four sides of
the container, or an overall padding value that applies to all of the sides at once. If a
container has specified a DockPadding value of 10, for example, a control docked the left will be will be
positioned 10 pixels away from the left edge.
Undocking: If none option is selected then dock of a control is disabled means the control
Figure:
Forms
A Form is used in VB.NET to create a form-based or window-based application. Using the form,
we can build a attractive user interface.
It is like a container for holding different control that allows the user to interact with an
application.
The controls are an object in a form such as buttons, Textboxes, Text area, labels, etc. to perform
some action. However, we can add any control to the runtime by creating an instance of it.
A Form uses a System.Windows.Form namespace, and it has a wide family of controls that add
both forms and functions in a Window-based user interface.
75
On the Create a new project window, select the Windows Forms App (.NET Framework)
template for Visual Basic.
Click OK
Window Form gets placed.
Resizing the form
When a form is created, the size and location is initially set to a default value. The default size of a form
is generally a width and height of 800x500 pixels. The initial location, when the form is displayed,
depends on a few different settings.
1. After adding a new form to the project, the size of a form is set in two different ways. First, you
can set it is with the size grips in the designer. By dragging either the right edge, bottom edge, or
the corner, you can resize the form.
2. The second way you can resize the form while the designer is open, is through the properties
pane. Select the form, then find the Properties pane in Visual Studio. Scroll down to size and
expand it. You can set the Width and Height manually in Properties window.
Resize in code
Even though the designer sets the starting size of a form, you can resize it through code. For example, if
you have Form1 with a button on it, that when clicked invokes the Click event handler to resize the
form:
private void button1_Click(object sender, EventArgs e)
Size = new Size (250, 200);
Properties Window
1. This window (also known as the Properties Browser) displays all the properties of the
selected component and its settings.
2. A property is a piece of information that characterizes a control. It could be related to its
location or size. It could be its color, its identification, or any visual aspect that
gives it presence on the screen. The properties of an object can be changed either at
design time or at run time.
3. You can also manipulate these characteristics both at design and at run times. This means
that you can set some properties at design time and some others at run time.
4. To manipulate the properties of a control at design time, first click the desired
property from the Toolbox. Then add it to the form or to a container control. To
change the properties of a control at design time, on the form, click the control to
select it. Then use the Properties window.The user is permitted to change the properties
according to his desire.
5. Every time you place a control on a form, you switch to this window to adjust the
appearance of the control.
Some of the events and properties of a properties window are listed below in table-01 and
table—02
The following are the most important list of events related a form:(table—01)
76
The following are the most important list of properties related to a form. And these properties can be
set or read while the application is being executed.
table-02
77
Solution Explorer
The Solution Explorer, which is the right side of the Visual Studio .NET window, provides an
organized view of your projects and their files.
The Solution Explorer window contains a list of the items in the current solution. It contains
details about your current project. A solution can contain multiple projects, and each project can
contain multiple items.
Solution Explorer has options to view the code, form design, refresh listed files. Projects files are
displayed in a drop down tree like structure, widely used in Windows based GUI applications.
In the Solution Explorer, you can open items for editing and add new items to a solution. You
can also search for files within a solution.
The Solution Explorer toolbar has the following buttons:
The View Code button opens the selected script for editing in the Code Editor.
The Refresh button updates the Solution Explorer display with information from the database.
The Show All Files button Show displays all the project items for the selected project, including
those that have been excluded and those that are normally hidden.
The Properties button Properties button displays the properties for the selected item in the
appropriate window.
Right-clicking on a project or test asset listed in the Solution Explorer displays various menu options,
some of them are listed below:
Rename
Import
Export
Remove
Delete
Debug
Project and so on.
78
type the desired value, and press Enter.
Expandable Fields: Some fields have a + button. This indicates that the property has
a set of sub-properties that actually belong to the same property and are set together.
To collapse the field, click the – button. Some of the properties are numeric based,
such as the above Size. With such a property, you can click its name and type two
numeric values separated by a comma.
Boolean Fields: Some fields can have only a true or false value. To change their
setting, you can either select from the combo box or double-click the property to
toggle to the other value.
Action Fields: Some fields would require a value or item that needs to be set through
an intermediary action. Such fields display an ellipsis button. When you click the
button, a dialog box would come up and you can set the value for the field.
There are various types of selection fields. Some of them display just two items. To
change their value, you can just double-click the field. Some other fields have more
than two values in the field. To change them, you can click their arrow and select
from the list. You can also double-click a few times until the desired value is selected.
Code:
Public Class Form1
Output:
Debug and enter two number click add button to get the result.
79
Execution of VB.NET applications can be done in following ways:
Press the F5 key.
On the VB menu bar, Run > Start.
On the VB toolbar, click the VB Run icon (the green arrow)
80
Keywords
A keyword is a reserved word with special meanings in the compiler, whose meaning cannot be
changed. Therefore, these keywords cannot be used as an identifier in VB.NET programming such as
class name, variable, function, module, etc.
Some of the keywords of VB.NET:
And , As , ByRef , By Val, Byte, Case, Catch, Char, Date, Dim, Decimal, Declare, Default, Do, Double, End,
EndIf , Else, For ,Next, Finally, Handles, Me, ReDim, Short, Long, Sub, While,Module , MyBase ,Namespace
Executable statements − these are the statements, which initiate actions. These statements can
call a method or function, loop or branch through blocks of code or assign values or expression
to a variable or constant. In the last case, it is called an Assignment statement.
Conditional Statements
If Then statement
If the condition evaluates to true, then the block of code inside the If statement will be executed. If
condition evaluates to false, then the first set of code after the end of the If statement (after the closing
End If) will be executed.
Syntax:
If condition Then
Statements
End If
Example program:
Module decisions
Sub Main()
Dim a As Integer = 10 ‘declaration
Syntax:
If(boolean_expression)Then
'statements will execute if the Boolean expression is true
Else
'statements will execute if the Boolean expression is false
81
End If
Example Program:
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
……..
[ Case Else
…statements]
End Select
Example Program:
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
82
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
Looping statements
For Next
A For Next loop is used to repeatedly execute a sequence
of code or a block of code until a given condition is satisfied.
A For loop is useful in such a case when we know how many
times a block of code has to be executed. In VB.NET, the For loop
is also known as For Next Loop.
Syntax:
For counter=start value To end value
[ Statements to be executed ]
Next
Example Program:
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20 step 2
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
Output:
value of a: 10
value of a: 12
value of a: 14
value of a: 16
value of a: 18
value of a: 20
Syntax:
For Each element [ As datatype ] In group
[ statements ]
Next [ element ]
Example Program:
Module loops
Sub Main()
83
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module
While statement
The While End loop is used to execute blocks of code or
statements in a program, as long as the given condition is
true. If the condition is true, the body of the while loop
is executed. This process of repeated execution of the body
continues until the condition is not false. And if the
condition is false, control is transferred out of the loop.
Syntax:
While condition
[ statements ]
End Whil
Example Program:
Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution '
While a < 20
Console.WriteLine("value of a: {0}", a)
a=a+1
End While
Console.ReadLine()
End Sub
End Module
Do While statement
It repeats the enclosed block of statements while a Boolean
condition is True or until the condition becomes True. It could be
terminated at any time with the Exit Do statement.
It means that it executes the Do statements, and then it checks the
condition.
Syntax:
Do { While | Until } condition
[ statements ]
Loop
-or-
Do
[ statements ]
Loop { While | Until } condition
Example Program:
84
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
a=a+1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
ARRAYS IN VB.NET
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _"Shivangi", "Ashwitha", "Somnath"}
Fixed-size array: The size of array always remains the same-size doesn't change during the program
execution. It means that we have defined the number of elements in the array declaration that will
remain the same during the definition of the elements, and its size cannot be changed.
Syntax:
Dim numbers(5) As Integer
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays . A
multi-dimensional array is an array with more than one subscript or dimension.
Syntax:
Dim Arr(10, 20) As Integer //2d array
Dim Arr(10,10,10)As Integer //3d array
Example Program:
Module arrays
85
Sub Main()
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
Ouput:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Arrays
Sometimes the a jagged array called as “array of arrays” and it can store arrays instead of a particular
data type value. A jagged array is a one-dimensional array whose elements contain arrays.
Syntax:
Dim scores As Integer()() = New Integer(5)(){
Example Program:
Module arrays
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
Dynamic Arrays
86
The size of the array can be changed at the run time- size changes during the program execution.
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as per the need of the program.
You can declare a dynamic array using the ReDim statement.
The Preserve keyword helps to preserve the data in an existing array, when you resize it.
Syntax:
ReDim [Preserve] arrayname(subscripts)
Example Program:
Module arrays
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
For i = 0 To 10
Console.WriteLine( marks(i))
Next i
Console.ReadKey()
End Sub
End Module
Output:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
UNIT 3
Application development on .NET
Building Windows Application
Steps:
First, open the Visual Studio then Go to File -> New -> Project to create a new project and then select the
language as Visual C# or Visual Basic from the left menu. Click on Windows Forms App(.NET Framework)
in the middle of current window. After that give the project name and Click OK
87
After that following window will display which will be divided into three parts as follows:
Editor Window or Main Window: Here, you will work with forms and code editing. You can notice the
layout of form which is now blank. You will double click the form then it will open the code for that.
Solution Explorer Window: It is used to navigate between all items in solution. For example, if you will
select a file form this window then particular information will be display in the property window.
Properties Window: This window is used to change the different properties of the selected item in the
Solution Explorer. Also, you can change the properties of components or controls that you will add to the
forms.
Now to add the controls to your WinForms application go to Toolbox tab present in the extreme left side of
Visual Studio. Here, you can see a list of controls. To access the most commonly used controls go to Common
Controls present in Toolbox tab.
To run the program you can use an F5 key or Play button present in the toolbar of Visual Studio. To stop the
program you can use pause button present in the ToolBar. You can also run the program by going to Debug-
>Start Debugging menu in the menubar.
Timer
The timer control is a looping control used to repeat any task in a given time interval. Once the timer is
enabled, it generates a tick event handler to perform any defined task in its time interval property. It starts
when the start() method of timer control is called, and it repeats the defined task continuously until the timer
stops.
Property Meaning
Enabled Gets/sets whether the timer is running.
Interval Gets/sets the time in milliseconds between timer ticks.
88
Method Meaning
Start Starts the timer.
Stop Stops the timer.
Steps
Code/Program:
PictureBox
PictureBox control is used to display the images on Windows Form. The PictureBox control has an image
property that allows the user to set the image at runtime or design time.
Typically the PictureBox is used to display graphics from a bitmap, metafile, icon, JPEG, GIF, or PNG file.
Example: While applying for any exams through online you upload image into google form.
Properties of Picturebox
89
Image - The image property is used to display the image on the PictureBox of a Windows form.
BorderStyle- It is used to set the border style for the picture box in the windows form.
ImageLocation-It is used to set or get the path or URL of the image displayed on the picture box of
the window form.
Text - It is used to set text for the picture box controls in the window form.
Methods of Picturebox
GetStyle() - The GetStyle() method is used to get values for the specified bit style in the PictureBox
control.
Load() - The Load() method is used to load the specified image from the control using the
ImageLocation property.
Events of Picturebox
BackColorChanged - It occurs when the property of the backcolor is changed in the PictureBox
control.
Resize - The resize event occurs when the picture box control is changed.
Steps
Step 1: We have to find the PictureBox control from the toolbox and then drag and drop the PictureBox
control onto the window form, as shown below.
Step 2: Once the PictureBox is added to the form, we can set various properties of the image by clicking on
the PictureBox control. And double click on the button write the below given code.
In the code we need to specify the path of the image that is to be displayed
Output:
1. The ComboBox control is used to display a drop-down list of various items. It is a combination of a
text box in which the user enters an item and a drop-down list from which the user selects an item. An
editable text field, giving the user multiple ways to input or select the desired information.
2. The ListBox control enables you to display a list of items to the user that the user can select by
clicking.
Properties of Combobox
MaxDropDownItems - The MaxDropDownItems property is used in the combo box control to
display the maximum number of items by setting a value.
MaxLength - It is used by the user to enter maximum characters in the editable area of the combo
box.
SelectedItem - It is used to set or get the selected item in the ComboBox Control.
Sorted - The Sorted property is used to sort all the items in the ComboBox by setting the value.
Events of ComboBox
FontChanged - It occurs when the property of the font value is changed.
Format - When the data is bound with a combo box control, a format event is called.
SelectIndexChanged - It occurs when the property value of SelectIndexChanged is changed.
Steps:
Step 1: We need to drag the combo box control from the toolbox and drop it to the Windows form, as shown
below.
Step 2: Once the ComboBox is added to the form, we can set various properties of the ComboBox by clicking
on the ComboBox control.Also drag and drop listbox and buttons .Write the code as given below
91
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("TROUSERS")
ComboBox1.Items.Add("TSHIRTS")
ComboBox1.Items.Add("JACKETS")
ComboBox1.Items.Add("JEANS")
ComboBox1.Text = "CLOTHING"
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs)
Handles ComboBox1.SelectedIndexChanged
Label1.Text = ComboBox1.SelectedItem.ToString()
End Sub
Listbox
GroupBox
In Windows form, GroupBox is a container which contains multiple controls on it and the controls are related
to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable
optional title. Or a GroupBox is used to categorize the related controls in a group.
The main use of a group box is to hold a logical group of RadioButton controls.
Properties of Groupbox:
AutoSize -This property is used to get or set a value that indicates whether the control resizes based
on its contents.
AutoSizeMode - This property indicates how the GroupBox behaves when its AutoSize property is
enabled.
BackColor - This property is used to get or set the background color for the control.
BorderStyle -This property indicates the border style for the control.
Size - This property is used to get or set the height and width of the control.
Visible - This property is used to get or set a value indicating whether the control and all its child
controls are displayed.
Width - This property is used to get or set the width of the control.
Steps
92
To create a GroupBox control at design-time, you simply drag and drop a GroupBox control from
Toolbox to a Form in Visual Studio. After you drag and drop a GroupBox on a Form. Once a
GroupBox is on the Form, you can move it around and resize it using mouse and set its properties and
events.
Also drag and drop radiobuttons and button user needs to select the option from given courselist and
submit.
Output:
Groupbox
Scrollbars
Vertical scrollbar
Horizontal scrollbar
A ScrollBar control is used to create and display vertical and horizontal scroll bars on the Windows form. It is
used when we have large information in a form, and we are unable to see all the data. Therefore, we used
VB.NET ScrollBar control. Generally, ScrollBar is of two types: HScrollBar for displaying scroll bars and
VScrollBar for displaying Vertical Scroll bars.
Properties of Scrollbars
BackColor - The BackColor property is used to set the back color of the scroll bar.
Maximum - It is used to set or get the maximum value of the Scroll Bar control. By default, it is 100.
Minimum - It is used to get or set the minimum value of the Scroll bar control. By default, it is 0.
Value- It is used to obtain or set a value in a scroll bar control that indicates a scroll box's current
position.
Events of scrollbars
Scroll - Occurs when the scroll box is moved either using mouse or keyboard.
93
ValueChanged - Occurs when the value property has changed by Scroll event or in code
Steps
Step 1: The first step is to drag the HScrollBar and VScrollBar control from the toolbox and drop it on to the
form.
Step 2: Once the ScrollBar is added to the form, we can set various properties of the ScrollBar by clicking on
the HScrollBar and VScrollBar control. Write the code as given below
Me.HScrollBar1.Minimum = 0
Me.HScrollBar1.Maximum = 100
Me.HScrollBar1.Value = 35
End Sub
End Class
NumericUpDown
The Windows Forms NumericUpDown control looks like a combination of a text box and a pair of arrows that
the user can click to adjust a value. The control displays and sets a single numeric value from a list of choices.
Example: If we want to enter our age in google form numericupdown is used.
1. DecimalPlaces: Gets or sets the number of decimal places to display in NumericUpDown Control.
2. UpDownAlign: Set positions the arrow buttons on the left or the right side of the NumericUpDown.
Default value is Right.
Steps
To create a NumericUpDown control at design-time, you simply drag and drop a NumericUpDown
control from Toolbox to a Form in Visual Studio.
Once a NumericUpDown is on the Form, you can move it around and resize it using mouse and set its
properties and events.Drag a button and double click on the button write the below code.
The ToString method is used to return a string representation of an object.
String format() method returns a formatted string using the given locale, specified format string, and
arguments
Code/Program :
94
Output:
ProgressBar
The ProgressBar control is typically used when an application performs tasks such as copying files or printing
documents.
The Window ProgressBar control is used by the user to acknowledge the progress status of some defined
tasks, such as downloading a large file from the web, copying files, installing software, calculating complex
results, and more.
The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and Maximum
properties are used to set the minimum and maximum values that the progress bar can display. The Value
property specifies the current position of the progress bar.
Properties of Progressbar
Maximum - It is used to set the maximum length of the progress bar control in the windows form.
Minimum - It is used to set or get the minimum value of the progress bar control in the windows
form.
Padding - The padding property is used to create a space between the edges of the progress bar by
setting the value in the progressbar control.
Events of ProgressBar
Leave - The Leave event occurs when the focus leaves the progress bar control.
MouseClick - A MouseClick event occurred when the user clicked on the progress bar control by the
mouse.
Methods of ProgressBar:
ForeColor - The ForeColor method is used to reset the forecolor to its default value.
ToString - The ToString method is used to display the progress bar control by returning the string.
Increment - It is used to increase the current state of the progress bar control by defining the specified
time.
Steps
Step 1: The first step is to drag the ProgressBar control from the toolbox and drop it on to the Form.
Step 2: Once the ProgressBar is added to the Form, we can set various properties of the ProgressBar by
clicking on the ProgressBar control. Drag a button so that when user click on button starts downloading
Code/Program:
Public Class Progressbar
95
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
ProgressBar1.Visible = True
Dim i As Integer
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 100
End If
Next
MsgBox("Successfully Completed")
End Sub
End Class
Output:
TrackBar
The Windows Forms TrackBar control (also sometimes called a "slider" control) is used for navigating
through a large amount of information or for visually adjusting a numeric setting. The TrackBar control has
two parts: the thumb, also known as a slider..
Example: Phone Brightness, Youtube videos.
Properties
The key properties of the TrackBar control are Value, TickFrequency, Minimum, and Maximum.
TickFrequency is the spacing of the ticks. Minimum and Maximum are the smallest and largest values
that can be represented on the track bar. Two other important properties are SmallChange and
LargeChange.
The value of the LargeChange property is the number of positions the thumb moves in response to
having the PAGE UP or PAGE DOWN key pressed, or in response to mouse clicks on the track bar
on either side of the thumb.
Steps
Step1:To create a TrackBar control at design-time, you simply drag and drop a TrackBar control from
Toolbox to a Form in Visual Studio. After you drag and drop a TrackBar on a Form,
Step2: You can configure ranges through which the value of the Value property of a track bar scrolls by
setting the Minimum property to specify the lower end of the range and the Maximum property to specify the
upper end of the range.
96
Code/Program:
End Sub
End Class
Output:
PROCEDURE
SUBROUTINE FUNCTION
DOES NOT RETURN VALUE RETURNS A VALUE TO CALLING
TO CALLING FUNCTION FUNCTION
Subroutine
A Sub procedure also called as subroutine is a separate set of codes that are used in VB.NET programming to
execute a specific task, when it is called and it does not return any values. The Sub procedure is enclosed by
the Sub and End Sub statement. The Sub procedure is similar to the function procedure for executing a
specific task except that it does not return any value, while the function procedure returns a value.
97
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200 ' local variable definition
swap(a, b) ' calling a function to swap the values '
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
Pass by Reference
Refer same above program instead ByVal put ByRef
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x
x=y
y = temp
End Sub
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200 ' local variable definition
swap(a, b) ' calling a function to swap the values '
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
Functions
A function procedure is a group of VB.NET statements. It begins with a Function keyword and ends with an
End Function keyword. It is generally used to perform a task and return a value back to the calling code. It has
return keyword .
Subroutines usually perform actions and they don't return any result. Functions, on the other hand, perform
some calculations and return a value.
There are two types of Functions:
1. User-Defined
2. Built-in functions
Syntax for Functions:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Program:
Passing by Value
Module Find_Sum
' Create the Sum() Function and pass the parameters.
Function Sum(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Dim sum As Integer = 0 ‘local variable
sum = n1 + n2
Return sum
End Function
Dim a As Integer = 50
Dim b As Integer = 20
Dim total As Integer
total = Sum(a, b) ‘calling function
98
Console.WriteLine(" Sum of two number is : {0}", total)
Console.ReadKey()
End Sub
End Module
Passing By Reference
Refer same above program instead ByVal put ByRef
Module Find_Sum
' Create the Sum() Function and pass the parameters.
Function Sum(ByRef n1 As Integer, ByRef n2 As Integer) As Integer
Dim sum As Integer = 0 ‘local variable
sum = n1 + n2
Return sum
End Function
Dim a As Integer = 50
Dim b As Integer = 20
Dim total As Integer
total = Sum(a, b) ‘calling function
Console.WriteLine(" Sum of two number is : {0}", total)
Console.ReadKey()
End Sub
End Module
Visual Basic has many built-in functions for manipulating text and carrying out mathematical operations, as
well as the ability to format data in both standard and user-defined styles.
Some of the built-in functions are explained below:
MsgBox() Function
The MsgBox() function displays a message in a pop-up message box . The user is expected to respond by
clicking on a button in order to be able to continue.
returnVal = MsgBox (prompt, styleVal, title)
The prompt parameter is a string value that supplies the message to be displayed.
The returnVal value returned by the MsgBox() function is an integer value that indicates which button
the user has clicked in response to the message box being displayed.
The title parameter is another string literal or string variable that supplies the title for the message box.
Example: MsgBox(messageText.Text, vbYesNo Or vbQuestion)
vbOkOnly Ok
vbYesNo Yes,No
vbOkCancel Ok,Cancel
vbAbort Abort
vbRetry Retry
vbYesNoCancel Yes,No,Cancel
vbIgnore Ignore
vbRetryCancel Retry,Cancel
99
InputBox() Function
The InputBox() function displays a pop-up input box into which the user can type a message. The user is
expected to enter their message, then click on a button ("Cancel" or "OK") in order to continue.
The returnString returned by the InputBox() function is the text entered by the user.
The defaultText parameter can be used to enter default content in the input box (although it would
probably be left blank in most cases).
The xpos and ypos parameters specify the x and y coordinates for the input box on screen.
String Functions
UCase (str) Converts the string referred to by str to all upper-case characters, and returns the result.
LCase (str) Converts the string referred to by str to all lower-case characters, and returns the result.
Trim (str) Removes the white space (if any) at either end of the text string referred to by str .
LTrim (str) Removes the white space (if any) at the left-hand end of the text string referred to by str
RTrim (str) Removes the white space (if any) at the right-hand end of the text string referred to by str
Maths functions
Formatting numbers
The Format() function allows you to specify precisely how numeric values are displayed. The function is used
as follows:
100
Percent Displays n as a percentage, rounds it up (or down) to
two decimal places, and adds a "%" symbol.
The Format() function can also be used to specify how date and time values are displayed. The function is
used as follows:
"General Date" Displays the date and time in the format: dd/mm/yyyy hh:mm:ss
"Long Date" Displays the date in the format: 06 October 2009
"Short Date" Displays the date in the format: dd/mm/yyyy
"Long Time" Displays the time in the format: h:mm:ss
Database Applications
Database systems are designed to manage large bodies of information. Management of data involves both
defining structures for storage of information and providing mechanisms for the manipulation of information.
Databases are useful in many different scenarios for storing data. It is typical to use a database when different
sets of data needs to be linked together, such as:
Pupils in a school and their grades,Customer records and sales information,Patients’ and doctors’
records,Transactions between different bank accounts,Taxpayers and income tax payments
Database Applications:
Social Media Sites − By filling the required details we are able to access social media platforms. Many users
sign up daily on social websites such as Facebook, Pinterest and Instagram. All the information related to the
users are stored and maintained with the help of DBMS.
Finance − Now-a-days there are lots of things to do with finance like storing sales, holding information and
finance statement management etc. these all can be done with database systems.
Military − In military areas the DBMS is playing a vital role. Military keeps records of soldiers and it has so
many files that should be kept secure and safe. DBMS provides a high security to military information.
Online Shopping − Now-a-days we all do Online shopping without wasting the time by going shopping with
the help of DBMS. The products are added and sold only with the help of DBMS like Purchase information,
invoice bills and payment.
Banking − Banking is one of the main applications of databases. We all know there will be a thousand
transactions through banks daily and we are doing this without going to the bank. This is all possible just
because of DBMS that manages all the bank transactions.
Manufacturing − Manufacturing companies make products and sell them on a daily basis. To keep records of
all those details DBMS is used.
Airline Reservation system − Just like the railway reservation system, airlines also need DBMS to keep
records of flights arrival, departure and delay status.
101
Library Management System − Now-a-days it’s become easy in the Library to track each book and maintain
it because of the database. This happens because there are thousands of books in the library. It is very difficult
to keep a record of all books in a copy or register. Now DBMS used to maintain all the information related to
book issue dates, name of the book, author and availability of the book.
1. Accurate
A database is pretty accurate as it has all sorts of build in constraints, checks etc. This means that the
information available in a database is guaranteed to be correct in most cases.
3. Security of data
Databases have various methods to ensure security of data. There are user logins required before
accessing a database and various access specifiers. These allow only authorised users to access the
database.
4. Data integrity
This is ensured in databases by using various constraints for data. Data integrity in databases makes
sure that the data is accurate and consistent in a database.
ADO.NET Connectivity
INTRODUCTION TO ADO.NET
ADO.NET stands for ActiveX Data Object is a large set of .NET classes that enable us to retrieve
and manipulate data, and update data sources, in very many ways.
ADO.NET is a bridge between the user application(frontend) and server(backend).Data coming from
application must be stored in database and ADO.NET provides various classes to store the data.
It is a module of .Net Framework which is used to establish connection between application and data
sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that can be
used to connect, retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes located
into System.Xml.dll.
102
ADO.NET has two main components that are used for accessing and manipulating data are the .NET
Framework data provider and the DataSet.
Dataprovider A .NET Framework data provider is used for connecting to a database, executing
commands, and retrieving results.
Dataset The DataSet, which is an in-memory cache of data retrieved from a data source, is a major
component of the ADO.NET architecture
DataProvider
ADO vs ADO.NET
ADO ADO.NET
o It is a COM(Component Object o It is a CLR(Common Language Runtime)
Modelling) based based Library.
o Library.
o Locking features is available o Locking features is not available
o ADO works in the connected mode to o ADO.Net works in the disconnected
access data mode to access data.
o Data is stored in Binary Format o Data is stores in XML
o XML integration is not possible o XML integration is possible
o It uses RecordSet to store the data from o It uses Dataset to store the data from
datasource datasource
o Using classic ADO, you can obtain o Dataset object of ADO.Net includes
information from one table or set of collection of DataTable wherein each
tables through join. You cannot fetch DataTable will contain records fetched
records from multiple tables from a particular table. Hence multiple
independently table records are maintained
independently
103
o In ADO, You can create only Client side o In ADO.Net, You can create both Client
cursor. & Server side cursor
o Firewall might prevent execution of o ADO.Net has firewall proof and its
Classic ADO execution will never be interrupted
o You cannot send multiple transaction o You can send multiple transaction using
using a single connection instance a single connection instance.
o ADO requires data to be converted to o ADO.NET does not require complex
data types supported by receiving system. conversions that wasted processor time.
o It has a less number of data types o It has a huge and rich collection of data
types.
o ADO is less secured. o ADO.NET much secured as compared to
ADO.
o ADO technology have less scalable. o ADO.NET have more scalability with the
use of locking mechanism.
o ADO have a poor performance. o In ADO.NET performance is much better
as compared to ADO.
o ADO technology use more resources as o ADO.NET conserves limited resources.
compared to ADO.NET.
Architecture of ADO.NET
It is a part of the .NET Framework which is used to establish a connection between the .NET Application and
different data sources. So, ADO.NET is nothing but a component in .NET Framework that helps us to fetch
data from different data sources(server) as well as also used to send data to different data sources(server) such
as SQL Server, Oracle, MySQL, XML, etc
The ADO.NET architecture comprises following important components. They are as follows:
1. Connection
104
2. Command
3. DataReader
4. DataAdapter
5. DataSet
Diagram
Dataprovider: It is a bridge between the user application and database. Data provider is used to connect to the
database, execute commands and retrieve the record. It is lightweight component with better performance.
They are the Microsoft SQL Server Data Provider , OLEDB Data Provider and ODBC Data Provider . SQL
Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses
OdbcConnection Object respectively.
Connection: The connection object is the first important component of your application. It is required to
connect to a backend database that may be SQL Server, Oracle, MySQL, etc. The connection is created using
the connection object and a backend data source must be connected to using the connection. To use this class,
you have to first create an object of this class. Hence, here we create a variable called 'cnn' which is of the type
SqlConnection.
Command: The second important component is the command object. When we discuss databases such as
SQL Server, Oracle, MySQL, then speak SQL, it is the command object that we use to create SQL queries.
After you create your SQL queries, you can execute them over the connection using the command object.
Example: select * FROM customers;
DELETE FROM customers WHERE city=’Mysuru’;
105
DataReader: We can only read the records in the forward mode with DataReader. Here, you should
familiarize yourself with three things: read-only, connected, and forward modes. The DataReader cannot be
created directly from code, they can created only by calling the ExecuteReader method of a Command Object.
The DataReader is a good choice when you're retrieving large amounts of data because the data is not cached
in memory.
reader = command.ExecuteReader();
DataSet: It is a Disconnected record set that can be browsed in both i.e. forward and backward mode. It is not
read-only i.e. you can update the data present in the data set. Actually, DataSet is a collection of DataTables
that holds the data and we can add, update, and delete data in a data table. DataSet gets filled by somebody
called DataAdapter. For example, the test scores of each student in a particular class is a data set.
DataAdapter: A data adapter a object serves as a bridge between a data set object and Data Source such as a
database to retrieve and save the data. Data adapter contains a set of database commands and a database
connection, which we use to fill a dataset object and update the Data Source.
DataReader
This class is used to read data from SQL Server database. We can only read the records in the forward mode
with DataReader. Here, you should familiarize yourself with three things: read-only, connected, and forward
modes. The DataReader cannot be created directly from code, they can created only by calling the
ExecuteReader method of a Command Object.
Properties
106
Connection It is used to get the SqlConnection associated with the
SqlDataReader.
Depth It is used to get a value that indicates the depth of nesting for the
current row.
GetValue(Int32) It is used to get the value of the specified column in its native format.
To create a SqlDataReader instance, we must call the ExecuteReader method of the SqlCommand object.
reader = command.ExecuteReader();
Program:
{
using (connection)
{
SqlCommand command = new SqlCommand( "SELECT CategoryID, CategoryName FROM
Categories;",connection);
connection.Open(); //connection open
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
conn.Close(); //connection close
}
Data Adapter
107
A data adapter a object serves as a bridge between a data set object and Data Source such as a database to
retrieve and save the data.Data adapter contains a set of database commands and a database connection, which
we use to fill a dataset object and update the Data Source.
We can also specify, which action we want to perform by using one of following four data adapter properties,
which executes a SQL statement.
The properties are given below.
Select command retrieves rows from Data Source
Insert command writes inserted rows from data set into Data Source
Update command writes modified rows from data set into Data Source.
Delete command deletes rows from Data Source.
Methods of DataAdapter:
FillUse this method of a SQL data adapter to add or refresh row from a Data Source and place them in
a Data Set table.
UpdateUse this method of data adapter object to transmit the changes to a dataset table to the
corresponding Data Source.
CloseUse this method for the connection to a database
Code/Program:
public partial class DataSetDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=student; integrated
security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con);
DataSet ds = new DataSet();
sde.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}
108
•Data Adapters: It communicate between a data source and dataset. We can use OleDbAdapter,
OdbcAdapter, Oracle Adapter or SqlAdapter.
• Command Objects: Data adapters can read, write, add, update and delete the records in a datasource. Data
adapters support 4 properties SelectCommand, InsertCommand, DeleteCommand, UpdateCommand.
• Dataset: The structure of a dataset is similar to relational database. It gives you access to an object model of
tables, rows and columns.
• Data Table: It holds a data table from a data source. It contain two properties: Columns and rows which is
collection of Datacolumn and Datarow objects.
•Data Reader: It hold a read only, forward only.
• Data Views: It represent a customized view of a single table that can be filtered, searched or sorted.
• Constraint Objects: Dataset supports constraint to check data integrity. Ex: Unique constraint and foreign
constraint
• Data Relation Objects: It specify a relationship between parent and child tables based on a key that share.
• Data Row/Column: A particular row/column in a data table
Joining Tables
We can to inner join, outer join using multiple tables.
ASP.NET
Programming web applications with web forms/ASP.NET applications with ADO.NET:
109
ASP.NET is a free web framework for building great websites and web applications using HTML, CSS,
and JavaScript.
ASP.NET is a web development platform, which provides a programming model, a comprehensive
software infrastructure and various services required to build up robust web applications for PC, as
well as mobile devices.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using
the extensible and reusable components or objects present in .Net framework. These codes can use the
entire hierarchy of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:
C#
Visual Basic.Net
Jscript
Web Forms:
Web Forms are pages that your users request using their browser. These pages can be written using a
combination of HTML, client-script, server controls, and server code. When users request a page, it is
compiled and executed on the server by the framework, and then the framework generates the HTML
markup that the browser can render. An ASP.NET Web Forms page presents information to the user in
any browser or client device.
Using Visual Studio, you can create ASP.NET Web Forms. The Visual Studio Integrated Development
Environment (IDE) lets you drag and drop server controls to lay out your Web Forms page. You can
then easily set properties, methods, and events for controls on the page or for the page itself. To write
server code to handle the logic for the page, you can use a .NET language like Visual Basic or C#.
ASP.NET has multiple features and provides many tools to create and develop web applications. Here
are some of the features of web forms:
1. Server Controls
It provides a vast set of server controls. These controls are like objects, and they run when they are
requested and rendered to the browser. Some web pages are similar to HTML elements like text-box,
button, checkbox, and hyperlink.
2. Mater Pages
Mater Pages is responsible for the consistent layout of our web applications. It gives a proper
appearance and standard to different pages.
3. Routing
110
URL routing can be configured to a web application. A request URL is a URL that a user enters in a
browser to browse in a specific place.
4. Security
Security always plays a crucial role in software development. ASP.NET provides different configuration
options and extensibility points to make our systems more secure.
Simple Example of Web Forms[should be written if any question asked upon ASP.NET]
Creating New Web Forms
To add a new form, select the project, right-click, and add a new item.
Click the web forms option in the left corner, and select web form.
Now click on the add button.
Double click on this form, and this will show some auto-generated code
111
Program:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<h1 style="text-align: center">Create Account</h1>
</div>
<table>
<tr>
<td>Enter Username:
</td>
<td>
<asp:TextBox ID="txtUserNameAC" runat="server" />
<asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please
enter Username" ControlToValidate="txtUserNameAC" runat="server" />
</td>
</tr>
<tr>
<td>Enter Password:
</td>
<td>
ControlToValidate="txtPWDAC" ErrorMessage="Please enter Password" />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="createAccountSubmit" runat="server" Text="Create
Account" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
112
cmd.Parameters.AddWithValue("@username", TextBox1.Text);
cmd.Parameters.AddWithValue("@Password", TextBox2.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("LoginPage.aspx");
}
else
{
Label3.Visible = true;
Label3.Text = "Wrong Details";
}
******GOOD LUCK******
-------------------------------------------------------------------------------------------------------------------------------------
113