52
52
.Net Framework
.NET is a software framework which is designed and developed by Microsoft. This Framework is used for
building and running applications on Windows. The first version of the .Net framework was 1.0 which came in the
year 2002. It supports running websites, services, desktop apps, and more on Windows. It is used to develop Form-
based applications, Web-based applications, and Web services. There is a variety of programming languages
available on the .Net platform.
The .Net framework consists of developer tools, programming languages, and libraries to build desktop and
web applications. It is also used to build websites, web services, and games.
In other words we can say, it is a virtual machine for compiling and executing programs written in different
languages like C#, VB.Net etc. It provides a lot of functionalities and also supports industry standards.
.NET Framework supports more than 60 programming languages in which 11 programming languages are
designed and developed by Microsoft.
Programming Languages which are designed and developed by Microsoft are:
1. C#.NET
2. VB.NET
3. C++.NET
4. J#.NET
5. F#.NET
6. JSCRIPT.NET
7. WINDOWS POWERSHELL
8. IRON RUBY
9. IRON PYTHON
10. C OMEGA
11. ASML(Abstract State Machine Language)
.NET Framework
Garbage Collector:
It is used to provide the Automatic Memory Management feature. If there was no garbage collector,
programmers would have to write the memory management codes which will be a kind of overhead on
programmers.
JIT (Just In Time Compiler):
It is responsible for converting the CIL(Common Intermediate Language) into machine code or native code
using the Common Language Runtime environment.
Microsoft Intermediate Language (MSIL)
A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it
compiles into an intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one
need not worry about the syntax of MSIL - since our source code in automatically converted to MSIL. The
MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language
which is then run on the host machine.
MSIL is similar to Java Byte code. A Java program is compiled into Java Byte code (the .class file) by a Java
compiler, the class file is then sent to JVM which converts it into the host machine language.
2. Framework Base Classes:- Base classes provide basic data types, collection of classes, method and other
general classes for use by .NET languages.
The .NET Framework includes a set of standard class libraries. A class library is a collection of methods and
functions that can be used for the core purpose.
For example, there is a class library with methods to handle all file-level operations. So there is a method which
can be used to read the text from a file. Similarly, there is a method to write text to a file.
Much of the functionality in the base framework classes resides in the vast namespace called System. We can
use the base classes in the system namespace for many different tasks including:
–Input/output Operations
–String Handling
–Managing arrays, lists, maps, etc
–Database Management
–Connecting to the Internet
–Accessing files and file systems
–And many more
3. User and Program Interfaces
The different types of applications that can be built in the .Net framework are classified broadly into the
following categories.
Windows forms
Web forms
Console Applications
Web Services
For example
WinForms – This is used for developing Forms-based applications, which would run on an end user machine.
Notepad is an example of a client-based application.
ASP.Net – This is used for developing web-based applications, which are made to run on any browser such as
Internet Explorer, Chrome or Firefox.
The Web application would be processed on a server, which would have Internet Information Services
Installed.
Internet Information Services or IIS is a Microsoft component which is used to execute an Asp.Net application.
The result of the execution is then sent to the client machines, and the output is shown in the browser.
Features of .Net
Microsoft .NET provides a framework that facilitates designing and developing applications that are portable,
scalable, and robust, and that can be executed in a distributed environment. It presents a platform and device-
independent computing model in a managed environment.
The Microsoft .NET framework provides a lot of features. Microsoft has designed the features of the .NET
framework by using the technologies that are required by software developers to develop applications for modern as
well as future business needs. The key features of .NET are:
1. Common Executive Environment:-
All .NET applications run under a common execution environment, called the Common Language Runtime. The
CLR facilitates the interoperability between different .NET languages such as C#, Visual Basic, Visual C++, etc. by
providing a common environment for the execution of code written in any of these languages.
2. Common Type System:-
The .NET framework follows types of systems to maintain data integrity across the code written in different .NET
compliant programming languages. CTS ensure that objects of the programs that are written in different
programming languages can communicate with each other to share data.
CTS prevent data loss when a type in one language transfers data to its equivalent type in one language transfer data
to its equivalent type in other languages. For example, CTS ensures that data is not lost while transferring an integer
variable of visual basic code to an integer variable of C# code.
The common type system CTS defines a set of types and rules that are common to all languages targeted at the
CLR. It supports both value and reference types. Value types are created in the stack and include all primitive types,
structs, and enums. In contrast, reference types are created in the managed heap and include objects, arrays,
collections, etc.
3. Multi-language support:-
.NET provides multi-language support by managing the compilers that are used to convert the source to
intermediate language (IL) and from IL to native code, and it enforces program safety and security.
The basis for multiple language support is the common type system and metadata. The basic data types used by the
CLR are common to all languages. There are therefore no conversion issues with the basic integer, floating-point
and string types.
All languages deal with all data types in the same way. There is also a mechanism for defining and managing new
types.
4. Tool Support:-
The CLR works hand-in-hand with tools like visual studio, compilers, debuggers, and profilers to make the
developer's job much simpler.
5. Security:-
The CLR manages system security through user and code identity coupled with permission checks. The identity of
the code can be known and permission for the use of resources granted accordingly. This type of security is a major
feature of .NET. The .NET framework also provides support for role-based security using windows NT accounts
and groups.
6. Automatic Resource Management:-
The .NET CLR provides efficient and automatic resource management such as memory, screen space, network
connections, database, etc. CLR invokes various built-in functions of .NET framework to allocate and de-allocate
the memory of .NET objects.
Therefore, programmers need not write the code to explicitly allocate and de-allocate memory to the program.
7. Easy and rich debugging support:-
The .NET IDE (integrated development environment) provides an easy and rich debugging support. Once an
exception occurs at run time, the program stops and the IDE marks the line which contains the error along with the
details of that error and possible solutions. The runtime also provides built-in stack walking facilities making it
much easier to locate bugs and error.
8. Simplified development:-
With .NET installing or uninstalling, a window-based application is a matter of copying or deleting files. This
possible because. .NET components are not referenced in the registry.
9. Framework class library:-
The framework class library (FCL) of the .NET framework contains a rich collection of classes that are available
for developers to use these classes in code Microsoft has developed these classes to fulfill various tasks of
applications, such as working with files and other data storages, performing input-output operations, web services,
data access, and drawing graphics.
The classes in the FCL are logically grouped under various namespaces such as system, System.collections,
system.diagnostics, system.Globalization, system.IO, system.text etc.
10. Portability:-
The application developed in the .NET environment is portable. When the source code of a program written in a
CLR compliant language complies, it generates a machine-independent and intermediate code. This was originally
called the Microsoft Intermediate Language (MSIL) and has now been renamed as the Common Intermediate
Language (CIL). CIL is the key to portability in .NET.
Applications that can be developed using .Net
When we hear .NET, the first idea that comes to our mind will probably be internet or networked applications.
Although this is absolutely true, there are many more types of applications to create with .NET.
So here is a more or less full list of various types of application that we can develop on .NET.
•ASP.Net Web applications are programs that used to run inside some web server to fulfill the user requests
over the http. ASP.NET Web applications can range from simple Web sites that consist of HTML pages to advanced
enterprise applications that run on local and remote networks. These enterprise applications also provide components
for exchanging data using XML. This type includes dynamic and data driven browser based applications. (Ex:
Hotmail and Google).
•Web services are “web callable” functionality available via industry standards like HTTP, XML and SOAP.
•Windows applications are form based standard Windows desktop applications for common day to day tasks.
(Ex: Microsoft word). Run only under Windows environment. These applications consume the services provided by
the Windows operating system.
•Windows services are long-running executable applications that run on the system as a background process.
These applications do not interfere with the working of the other processes that run on the same computer. Windows
services execute within separate Windows sessions created specifically for each Windows service. These services do
not have a graphic user interface and are ideal for running on the server. Windows services were earlier called NT
services.
•Console applications are light weight programs run inside the command prompt (DOS) window. They are
commonly used for test applications.
•Mobile applications can run on multiple mobile devices, such as Pocket PCs, mobile phones, or personal
digital assistants. These applications provide ubiquitous access to data from mobile devices. The .NET Framework
automatically makes changes to these applications to enable them to run on multiple browsers, depending on the
mobile device.
•Class libraries are components that we create once and reuse a number of times in multiple applications.
Class libraries allow us to define several classes, along with their methods and interfaces, in one file. These libraries
compile to .dll files and facilitate rapid development of new applications because of reusability of code. To access the
functionality of the classes in a class library from our application, we need to include a reference to that library in our
program.
All types of .NET applications use one or more .NET compliant languages for their design and development.
The .NET Framework includes various technologies, such as ASP.NET, VB.NET, VC++.NET, and ADO.NET. We
use ASP.NET to build Web applications and Web services, VB.NET and VC++.NET to create Windows
applications, and ADO.NET for flexible access to databases.
Unit-2
C# Features
C# is object oriented programming language. It provides a lot of features that are given below.
1. Simple
2. Modern programming language
3. Object oriented
4. Type safe
5. Interoperability
6. Scalable and Updateable
7. Component oriented
8. Structured programming language
9. Rich Library
10. Fast speed
1) Simple
It is quite simple to use C# as it has various features and functionalities. Moreover, it provides a structured
approach that makes the program easier to understand. It provides structured approach (to break the problem
into parts), rich set of library functions, data types etc. C# code does not require header files. All code is written
inline.
2) 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.
C# supports number of modem features, such as:
• Automatic Garbage Collection
• Error handling features
• Modern debugging features
• Robust Security features
3) Object Oriented
C# is pure 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.
In C#, everything is an object. There are no more global functions, variable and constants.
It supports all three object oriented features:
• Encapsulation
• Inheritance
• Polymorphism
4) Type Safe
Type safety promotes robust programming. Therefore it improves a security of the program. It will not allow us to
mix up one data type with the other data type.
5) Interoperability
Language interoperability is the ability of code to interact with code that is written using a different programming
language. Language interoperability can help maximize code reuse and, therefore, improve the efficiency of the
development process. It is the ability for two or more languages to interact as part of the same system. In other
words, two .NET compliant languages can interoperate with each other. This simply means a function in VB .NET
can be called by C# and vice-versa.
6) Scalable and Updateable
C# is an automatically scalable as well as updatable language. .NET has introduced assemblies which are self
describing by means of their manifest. Manifest establishes the assembly identity, version, culture and digital
signature etc. Assemblies need not to be register anywhere.
To scale our application we delete the old files and updating them with new ones. No registering of dynamic
linking library.
Updating software components is an error prone task. Revisions made to the code. This can affect the existing
program. C# support versioning in the language. Native support for interfaces and method overriding enable
complex frame works to be developed and evolved over time.
7) Component Oriented
C# is component oriented programming language. Component-oriented programming is a technique of
developing software applications by combining pre-existing and new components.
8) 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.
9) Rich Library
C# provides a lot of inbuilt functions that makes the development fast.
10) Fast Speed
The compilation and execution time of C# language is fast.
C# - Data Types
C# is a strongly-typed language. It means we must declare the type of a variable that indicates the kind of values it is
going to store, such as integer, float, decimal, text, etc.
The following declares and initialized variables of different data types.
Example: Variables of Different Data Types
string stringVar = "Hello World!!";
int intVar = 100;
float floatVar = 10.2f;
char charVar = 'A';
bool boolVar = true;
C# mainly categorized data types in two types:
Value types and Reference types.
Value types include simple types (such as int, float, bool, and char), enum types and struct types. Reference types
include class types, object types, interface types, delegate types, and array types.
Value Type
A data type is a value type if it holds a data value within its own memory space. It means the variables of these
data types directly contain values.
For example, consider integer variable int i = 100;
The system stores 100 in the memory space allocated for the variable i.
The following data types (with size) are all of value type:
Data Type Size
bool 1 bit
char 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes
enum User-defined data type
structure User-defined data type
Reference Type
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value
is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";
The following image shows how the system allocates the memory for the above string variable.
As we can see in the above image, the system selects a random location in memory (0x803200) for the variables.
The value of a variable s is 0x600000, which is the memory address of the actual data value. Thus, reference
type stores the address of the location where the actual value is stored instead of the value itself.
The followings are reference type data types:
String
Object
Arrays (even if their elements are value types)
Class
Delegate
Interface
Numbers
Number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types
are int and long. Which type we should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals. Valid types
are float and double.
Integer Types
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.
Example
int myNum = 100000;
Console.WriteLine(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used
when int is not large enough to store the value. Note that we should end the value with an "L": (although not
required):
Example
long myNum = 15000000000L;
Console.WriteLine(myNum);
Floating Point Types
We should use a floating point type whenever we need a number with a decimal, such as 9.99 or 3.14515.
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. It has 7 digits Precision. Note that we
should end the value with an "F":
Example
float myNum = 5.75F;
Console.WriteLine(myNum);
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. It has 14 – 15 digit Precision. Note
that we can end the value with a "D" (although not required because by default floating data types are the double
type.):
Example
double myNum = 19.99D;
Console.WriteLine(myNum);
Booleans
A boolean data type is declared with the bool keyword and can only take the values true or false:
Example
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
Characters
The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or
'c':
Example
char myGrade = 'B';
Console.WriteLine(myGrade);
Strings
The string data type is used to store a sequence of characters (text). String values must be surrounded by double
quotes:
Example
string greeting = "Hello World";
Console.WriteLine(greeting);
Type Default
char '\x0000'
float 0.0f
double 0.0d
decimal 0.0m
bool false
object null
string null
As we can see, for the integral value types, the default value is zero. The default value for the char type is the
character equivalent of zero and false for the bool type. The object and string types have a default value of null,
Or we can say that all value type has default value zero and all reference type default value is null.
C# | Identifiers
In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the
user-defined name of the program components. In C#, an identifier can be a class name, method name, variable
name or label.
Example:
public class program
{
public static void Main()
{
int x;
}
}
Here the total number of identifiers present in the above example is 3 and the names of these identifiers are:
Constants
However, we can add the const keyword if we don't want others (or our self) to overwrite existing values (this will
declare the variable as "constant", which means unchangeable and read-only):
Example
const int myNum = 15;
myNum = 20; // error
The const keyword is useful when we want a variable to always store the same value.
Note: We cannot declare a constant variable without assigning the value. If we do, an error will occur: A const field
requires a value to be provided.
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";
C# Literals
Literals in C# are the fixed value used by a variable that is predefined and cannot be modified during the execution of
the code. These are the convenient form of constant values like other variables but their values cannot be changed.
The value used by a variable can be integer, decimal, floating type or string. There are different types of literals in C#
with different forms. There are various types of literals in C#.
1. Integer Literals
2. Floating-point Literals (Real Literals)
3. Character Literals
4. String Literals
5. Boolean Literals
Following are the different types of literals in C#.
1. Integer Literals
The literal of integer type can be octal, decimal or hexadecimal. The prefix is used to specify whether it is decimal,
octal or hexadecimal. U and u are also used as a suffix with integer type literals for unsigned numbers and l and L
used for long numbers. Every literal is of integer type by default.
Decimal Literals: In the decimal type of literals 0-9 digits are allowed. No prefix is required for the decimal
type of literals.
int x = 100; // decimal type
Octal Literals: In the octal type of literals 0-7 digits are allowed. 0 is used as a prefix to specify the form of
octal type literals.
int x = 072; // octal type
Hexa-decimal literals: In the hexadecimal type of literals, digits from 0- 9 and characters from A-f are
allowed. Uppercase and lowercase both types of characters are allowed in this case. 0X or 0x is used as a
prefix to specify the form of hexadecimal type of literals.
int x = 0x123f; // hexadecimal type
2. String Literals
The string type literals are enclosed in (“”)/ double quotes and also can be started with @””. Long lines can be broken
into multiple lines with string literals and be separated by using blank spaces.
string s= “Hi”; // string literals
3. Character Literals
The character type literals are enclosed in (‘’)/single quotes. There are three ways to specify character literals.
Single Quote: Characters literals can be specified as single char using a single quote.
Unicode Representation: Character literals can be specified using Unicode Representation ‘\uxxxx’ where
xxxx are the hexadecimal numbers.
Escape Sequence: There are some escape characters known as char literals.
char c = ‘\n’;
Following are some escape sequence literals explained with there meanings.
\\ Character
\’ Character
\’’ Character
\? Character
\a Alert
\b Backspace
\n Newline
\f Form feed
\v Vertical tab
using System;
namespace Literals
{
class Program
{
static void Main(string[] args)
{
int x = 212; // decimal literal
int y = 0145; // octal literal
int z = 0x4b; // hexadecimal literal
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.ReadLine();
}
}
}
Output:
212
145
75
Explanation: In the above example, there are various forms of integer type literals. In this no prefix is used for
decimal form, 0 is used to specify the octal form and 0x is used for specifying the hexadecimal number. Using prefix
we can define the form of integer type literal. In this code, first, there is a literal of decimal type with no prefix, a
second type is an octal form with 0 as prefix and at last, we have a hexadecimal type with 0x as a prefix.
Example #2 – Floating Point Literal
using System;
namespace Literals
{
class Program
{
static void Main(string[] args)
{
double x = 187.231;
double y = 0141.361;
double z = 374159E-4F;
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
Console.ReadLine();
}
}
}
Output:
187.231
141.361
37.415901184082
Explanation: In the above example, floating-point literals are implemented. It can be a decimal number, fractional or
any exponent. So we can represent it either in decimal or in exponential form. The floating type literal is of double
type. F or F can be used as a suffix to specify the value as it cannot be assigned directly to the float variable.
Hello World !
Explanation: In the above example, character type literals are implemented. In the above code, all three forms of
character type are shown. We can specify the character literal using a single quote, Unicode representation, and
escape sequence. We have multiple types of escape characters with their own meanings. In this code, the first single
quote character is specified where the second one has Unicode representation and then, at last, we have escape form
type of character literals.
Output:
This is C# programming
This is C# programming
Explanation: In the above example, string literals are implemented. There are two ways to specify string literals as
shown in the code. First, it is implemented using double quotes and then @ symbol is used to specify the string.
using System;
namespace Literals
{
class Program
{
static void Main(string[] args)
{
bool x = true;
bool y = false;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
}
}
}
Output:
True
False
Explanation: In the above example, Boolean type literals are implemented which has two value either true or false.
C# Syntax
Example
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Output
Hello World!
Example explained
Line 1: using System means that we can use classes from the System namespace.
Line 2: namespace is a used to organize our code, and it is a container for classes and other namespaces.
Line 3: The curly braces {} marks the beginning and the end of a block of code.
Line 4: class is a container for data and methods, which brings functionality to our program. Every line of code that
runs in C# must be inside a class. In our example, we named the class Program.
Line 5: Another thing that always appears in a C# program is the Main method. Any code inside its curly
brackets {} will be executed. Here M of Main should be capital.
Line 6: Console is a class of the System namespace, which has a WriteLine() method that is used to output/print
text. In our example it will output "Hello World!".
If we omit the using System line, we would have to write System.Console.WriteLine() to print/output text.
Note: Every C# statement ends with a semicolon ;.
Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.
static: It means Main Method can be called without an object. We need an entry point into our program. Static means
that we can call the function without having instance of a class (or creating object of class).
public: It is access modifiers which means the compiler can execute this from anywhere.
void: The Main method doesn’t return anything. Main can either have a void or int.
Main(): It is the configured name of the Main method.
String []args: For accepting the zero-indexed command line arguments. args is the user-defined name. So we can
change it by a valid identifier. [] must come before the args otherwise compiler will give errors. The Main method
can be declared with or without a string [] args parameter that contains command-line arguments.
Applicable Access Modifiers: public, private, protected, internal, protected internal access modifiers can be used
with the Main() method. The private protected access modifier cannot be used with it.
Display Variables
The WriteLine() method is often used to display variable values to the console window.
To combine both text and a variable, use the + character:
Example
string name = "Mohan";
Console.WriteLine("Hello " + name);
Output
Hello Mohan
For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables
here):
Example
int x = 5;
int y = 6;
Console.WriteLine(x + y); // Print the value of x + y
Output
11
C# Type Conversion
Type casting is when we assign a value of one data type to another type.
In C#, there are two types of casting:
Implicit Conversion (automatically) - converting a smaller type to a larger type size. These conversions are
performed by C# in a type-safe manner.
char -> int -> long -> float -> double
Explicit Conversion (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size type:
Example
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses () in front of the value:
Example
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
Type Conversion Methods
It is also possible to convert data types explicitly by using built-in methods, such
as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long):
Example
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string
C# User Input
We have already learned that Console.WriteLine() is used to output (print) values. Now we will
use Console.ReadLine() to get user input.
Example
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
Console.WriteLine("Username is: " + userName);
User Input and Numbers
The Console.ReadLine() method returns a string. Therefore, we cannot get information from another data type, such as int.
The following program will cause an error:
Example
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
We cannot implicitly convert type 'string' to 'int'.
We can convert any type explicitly, by using one of the Convert.To methods:
Example
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
Output
Enter your age:
18
Your age is: 18
Exercise1: Write a C# Sharp program to print the sum of two numbers.
class Exercise1
{
public static void Main()
{
System.Console.WriteLine(15+17);
}
}
Output:
32
Exercise2: Write a C# Sharp program to swap two numbers.
using System;
class Exercise2
{
public static void Main(string[] args)
{
int number1, number2, temp;
Console.WriteLine("Input the First Number : ");
number1 = Convert.ToInt32 (Console.ReadLine());
Console.WriteLine("Input the Second Number : ");
number2 = Convert.ToInt32 (Console.ReadLine());
temp = number1;
number1 = number2;
number2 = temp;
Console.WriteLine("After Swapping : ");
Console.WriteLine("First Number : "+number1);
Console.WriteLine("Second Number : "+number2);
}
}
Output:
Input the First Number : 2
Input the Second Number : 5
After Swapping :
First Number : 5
Second Number : 2
Exercise3: Write a C# Sharp program to print on screen the output of adding, subtracting, multiplying and
dividing of two numbers which will be entered by the user.
using System;
class Exercise3
{
public static void Main()
{
Console.Write("Enter a number: ");
int num1= Convert.ToInt32(Console.ReadLine());
Exercise4: Write a C# Sharp program that takes four numbers as input to calculate and print the average.
using System;
class Exercise4
{
public static void Main()
{
double number1,number2,number3,number4;
Exercise 5: Write a program in C# Sharp to read 10 numbers from keyboard and find their sum and average.
using System;
class Exercise4
{
public static void Main()
{
int i,n,sum=0;
double avg;
Console.WriteLine("Input the 10 numbers : \n");
for (i=1;i<=10;i++)
{
Console.WriteLine("Number-{0} :",i);
n= Convert.ToInt32(Console.ReadLine());
sum +=n; // sum=sum+n
}
avg=sum/10.0;
Console.WriteLine("The sum of 10 no is : {0} The Average is : {1}\n",sum,avg);
}
}
Output:
Input the 10 numbers :
Number-1 :2
Number-2 :4
Number-3 :6
Number-4 :8
Number-5 :10
Number-6 :12
Number-7 :14
Number-8 :16
Number-9 :18
Number-10 :20
The sum of 10 no is : 110
The Average is : 11
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that have contiguous memory
location. That is, arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value. In C#, array is an object of base type System.Array. In C#, array index starts from 0. We can store
only fixed set of elements in C# array.
Declaring Arrays
To declare an array in C#, we can use the following syntax −
datatype[] arrayName;
where,
datatype is used to specify the data type of elements in the array.
[ ] specifies the rank of the array. The rank specifies the size of the array.
arrayName specifies the name of the array.
For example,
double[] balance;
int [] marks;
Note: We cannot place square brackets after the identifier.
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is initialized, we can assign
values to the array.
Array is a reference type, so we need to use the new keyword to create an instance of the array. For example,
double[] balance = new double[10];
Assigning Values to an Array
We can assign values to individual array elements, by using the index number, like −
double[] balance = new double[10];
balance[0] = 4500.0;
We can assign values to the array at the time of declaration, as shown −
double [] balance = {2340.0, 4523.69, 3421.0};
We can also create and initialize an array, as shown −
int [] marks = new int[5] { 99, 98, 92, 97, 95};
We may also omit the size of the array, as shown −
int [] marks = new int[] { 99, 98, 92, 97, 95};
// Create an array of four elements, omitting the new keyword, and without specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
We should note that if we declare an array and initialize it later, we have to use the new keyword:
Array Length
To find out how many elements an array has, use the Length property: as arrayName.Length
Example
using System;
class Program
{
public static void Main()
{
int[] marks = {1,10,15,20,25,30};
Console.WriteLine(marks.Length);
}
}
Output
6
Array Index
The IndexOf() method of array class in C# searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.
We have set the array.
Now use the IndexOf() method and set the element for which we want the index,
The following is the example showing the usage of IndexOf(,) method in C#.
Example
using System;
class Program {
static void Main() {
int[] arr = new int[5];
arr[0] = 100;
arr[1] = 200;
arr[2] = 300;
arr[3] = 400;
arr[4] = 500;
int a = Array.IndexOf(arr, 400);
Console.WriteLine(a);
}
}
Output
3
Loop Through an Array
We can loop through the array elements with the for loop, and use the Length property to specify how many times the
loop should run.
The following example outputs all elements in the marks array:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[] marks = {10,23,12,25,16};
for (int i = 0; i < marks.Length; i++)
{
Console.WriteLine(marks[i]);
}
}
}
}
Output
10
23
12
25
16
The example above can be read like this: for each string element (called i - as in index) in cars, print out the value
of i.
If we compare the for loop and foreach loop, we will see that the foreach method is easier to write, it does not require
a counter (using the Length property), and it is more readable.
Sort Arrays
There are many array methods available, for example Sort(), which sorts an array alphabetically or in an ascending
order: Example
using System;
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{
Console.WriteLine(i);
}
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
Console.WriteLine(i);
}
}
}
Output
BMW
Ford
Mazda
Volvo
1
5
8
9
System.Linq Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in the System.Linq namespace:
Example
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] myNumbers = {5, 1, 25, 9};
Console.WriteLine(myNumbers.Max()); // returns the largest value
Console.WriteLine(myNumbers.Min()); // returns the smallest value
Console.WriteLine(myNumbers.Sum()); // returns the sum of elements
}
}
Output
25
1
40
Another Example
Let's see a simple example of C# array, where we are going to declare, initialize and traverse array.
using System;
class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Output:
10
0
20
0
30
Example 2
using System;
class MyArray
{
static void Main(string[] args) {
int [] n = new int[10];
int i,j;
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
Console.WriteLine("Element[{0}] = {1}", i, n[i]);
}
}
}
Output −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Exercise5: Write a program in C Sharp to store elements in an array and print it.
using System;
class Exercise5
{
public static void Main()
{
int[] arr = new int[10];
int i;
Console.Write("Input 10 elements in the array :\n");
for(i=0; i<10; i++)
{
Console.WriteLine("element - {0} : ",i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\nElements in array are: ");
for(i=0; i<10; i++)
{
Console.WriteLine("{0}", arr[i]);
}
}
}
Exercise6: Write a program in C# to find the sum of all elements of the array.
using System;
public class Exercise6
{
public static void Main()
{
int[] a= new int[100];
int i, n, sum=0;
Console.Write("Input the number of elements to be stored in the array :");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Input {0} elements in the array :\n",n);
for(i=0;i<n;i++)
{
Console.Write("element - {0} : ",i);
a[i] = Convert.ToInt32(Console.ReadLine());
}
for(i=0; i<n; i++)
{
sum += a[i];
}
Console.Write("Sum of all elements stored in the array is : {0}\n\n", sum);
}
}
C# Multidimensional Arrays
So far, we have worked with one-dimensional arrays. The number of indexes needed to specify an element is called
the dimension, or rank of the array.
C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. We can declare a 2-
dimensional array of strings as –
string [,] names;
or, a 3-dimensional array of int variables as −
int [ , , ] m;
Two-dimensional array
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-
dimensional arrays.
A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns.
Following is a 2-dimensional array, which contains 3 rows and 4 columns −
Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the
array, and i and j are the subscripts that uniquely identify each element in array a.
System.Console.WriteLine(val);
System.Console.WriteLine(val2);
}
Special Characters
A text in the real world can include any character. In C#, because a string is surrounded with double quotes, it
cannot include " in a string. The following will give a compile-time error.
String Length
A string in C# is actually an object, which contain properties and methods that can perform certain operations on
strings. For example, the length of a string can be found with the Length property as: stringname.Length
Example
string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("The length of the alpha string is: " + alpha.Length);
Output
26
Other Methods
There are many string methods available, for example ToUpper() and ToLower(), which returns a copy of the string
converted to uppercase or lowercase:
Example
string txt = "Hello World";
Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower()); // Outputs "hello world"
String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:
Example
string firstName = "Ashish ";
string lastName = "Sharma";
string name = firstName + lastName;
Console.WriteLine(name); // Outputs "Ashish Sharma"
We can also use the string.Concat() method to concatenate two strings:
Example
string firstName = "Ashish ";
string lastName = " Sharma ";
string name = string.Concat(firstName, lastName);
Console.WriteLine(name); // Outputs "Ashish Sharma"
Access Strings
We can access the characters in a string by referring to its index number inside square brackets [].
This example prints the first character in myString:
Example
string myString = "Hello";
Console.WriteLine(myString[0]); // Outputs "H"
Example
string myString = "Hello";
Console.WriteLine(myString[1]); // Outputs "e"
C# Method Parameters
Parameters and Arguments
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. We can add as many parameters as we want, just
separate them with a comma.
The following example has a method that takes a string called fname as parameter. When the method is called, we
pass along a first name, which is used inside the method to print the full name:
Example
using System;
class Program
{
static void MyMethod(string name)
{
Console.WriteLine(name);
}
static void Main(string[] args)
{
MyMethod("Mohan");
MyMethod("Ashish");
MyMethod("Ankit");
}
}
Output
// Mohan
// Ashish
// Ankit
When a parameter is passed to the method, it is called an argument. So, from the example above: name is
a parameter, while Mohan, Ashish and Ankit are arguments.
Example 2
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
}
Output
// Liam is 5
// Jenny is 8
// Anja is 31
Example 3
using System;
namespace MyApplication
{
class Program
{
static int add(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine(add(5, 3));
}
}
}
Output
8
Note that when we are working with multiple parameters, the method call must have the same number of arguments
as there are parameters, and the arguments must be passed in the same order.
Exercise: Write a program in C# Sharp for the sum of two numbers (entered by user) by creating a function.
using System;
class funcexer3
{
static int Sum(int num1, int num2)
{
int total;
total = num1 + num2;
return total;
}
public static void Main()
{
Console.WriteLine("Enter a number: ");
int n1= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter another number: ");
int n2= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The sum of two numbers is : {0} ", Sum(n1,n2) );
}
}
C# Classes and Objects
C# is an object-oriented programming language.
Procedural programming is about writing procedures or methods that perform operations on the data, while object-
oriented programming is about creating objects that contain both data and methods.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code easier to maintain,
modify and debug
OOP makes it possible to create full reusable applications with less code and shorter development time
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
Class objects
Fruit Apple
Banana
Mango
Orange
So, a class is a template or blueprint for objects and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and methods from the class.
Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in real
life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
Create a Class
To create a class, use the class keyword:
Create a class named "Car" with a variable color:
class Car
{
string color = "red";
}
Create an Object
An object is created from a class. We have already created the class named Car, so now we can use this to create
objects.
To create an object of Car, specify the class name, followed by the object name, and use the keyword new:
Example
Create an object called "ford" and use it to print the value of color:
class Car
{
string color = "red";
public static void Main(string[] args)
{
Car ford = new Car();
Console.WriteLine(ford.color);
}
}
Output
red
Example
Create two objects of Car:
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj1 = new Car();
Car myObj2 = new Car();
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
}
}
Output
red
red
Class Members
Fields and methods inside classes are often referred to as "Class Members":
Example
Create a Car class with three class members: two fields and one method.
// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Fields
Variables inside a class are called fields, and that we can access them by creating an object of the class, and by using
the dot syntax (.).
The following example will create an object of the Car class, with the name myObj. Then we print the value of the
fields color and maxSpeed:
Example
class Car
{
string color = "red";
int maxSpeed = 200;
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
Output
red
200
We can also leave the fields blank, and modify them when creating the object:
Example
class Car
{
string color;
int maxSpeed;
static void Main(string[] args)
{
Car myObj = new Car();
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
Output
red
200
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
Output
Mustang
Astra
Object Methods
Methods are used to perform certain actions.
Methods normally belong to a class, and they define how an object of a class behaves.
Just like with fields, we can access methods with the dot syntax. However, note that the method must be public. The
reason is simple: a static method can be accessed without creating an object of the class, while public methods can
only be accessed by objects. And remember that we use the name of the method followed by two parantheses () and
a semicolon ; to call (execute) the method:
Example
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
Output
The car is going as fast as it can!
Example
using System;
class Student
{
string course;
int rollno;
public void Performance()
{
Console.WriteLine("Hard work is the key of success");
}
class base_class
{
...
}
class derived_class : base_class
{
...
}
Let’s understand this by taking simple example of inheritance:
Example 1
using System;
class myclass1
{
public int i =10;
}
class program
{
public static void Main()
{
myclass2 obj = new myclass2();
Console.WriteLine(obj.i);
Console.WriteLine(obj.a);
Console.WriteLine(obj.i + obj.a);
}
}
Output
10
20
30
Example2
In the example below, the Car class (child) inherits the fields and methods from the Vehicle class (parent):
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
Output
Tuut, tuut!
Ford Mustang
The sealed Keyword
If we don't want other classes to inherit from a class, use the sealed keyword:
If we try to access a sealed class, C# will generate an error:
sealed class Vehicle
{
...
}
Types of Polymorphism
There are two types of polymorphism in C#:
Static / Compile Time Polymorphism.
Dynamic / Runtime Polymorphism.
Static or Compile Time Polymorphism
Method overloading
It is also known as Early Binding. Method overloading is an example of Static Polymorphism. In overloading, the
method / function has a same name but different arguments. It is also known as Compile Time Polymorphism
because the decision of which method is to be called is made at compile time. Overloading is the concept in which
method names are the same with a different set of parameters (may be different no of parameters, may be different
types of parameters).
Here C# compiler checks the number of parameters passed and the type of parameter and make the decision of which
method to call and it throw an error if no matching method is found.
In the following example, a class has two methods with the same name "Add" but with different input parameters (the
first method has two parameters and the second method has three parameters).
Example
using System;
class myclass1
{
public int ADD(int a, int b)
{
int c= a+b;
return c;
}
}
class myclass2 : myclass1
{
public int ADD(int a, int b, int c)
{
int d= a+b+c;
return d;
}
}
class program
{
public static void Main()
{
myclass2 obj = new myclass2();
Console.WriteLine(obj.ADD(5,6));
Console.WriteLine(obj.ADD(5,6,6));
}
}
Operator Overloading
The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use
the same operator to do various operations. It provides additional capabilities to C# operators when they are applied
to user-defined data types. The function of the operator is declared by using the operator keyword.
Syntax :
access specifier className operator Operator_symbol (parameters)
// Code
For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just
using +.
Example –(See the difference between below two programs- working of virtual and override keyword.)
using System;
class parent
{
public void method()
{
Console.WriteLine("This is a parent class method.");
}
}
Another Example
using System;
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myCat = new Cat(); // Create a Cat object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myCat.animalSound();
myDog.animalSound();
}
}
Output
The animal makes a sound
The animal makes a sound
The animal makes a sound
using System;
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myCat = new Cat(); // Create a Cat object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myCat.animalSound();
myDog.animalSound();
}
}
Output
The animal makes a sound
The cat says: meow meow
The dog says: bow wow
Example
using System;
class Animal
{
public virtual void eat()
{
Console.WriteLine("Eating...");
}
}
class Dog: Animal
{
public override void eat()
{
Console.WriteLine("Eating bones...because dog loves to eat bones.");
}
}
public class Overriding
{
public static void Main()
{
Animal myanimal = new Animal();
Animal tommy = new Dog();
tommy.eat();
}
}
Output:
Eating bones...because dog loves to eat bones.
C# Interface
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces.
Interface in C# is a blueprint of a class. Like a class, Interface can have methods, properties and events as its
members. 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.
Interfaces specify what a class must do, not how.
Interfaces can’t have private members.
By default all the members of Interface are public.
The interface will always defined with the help of keyword ‘interface’.
Interface cannot contain fields.
Multiple inheritances are possible with the help of Interfaces, which can't be achieved by class.
Its implementation must be provided by class.
Syntax for Interface Declaration:
interface <interface_name >
{
// declare Events
// declare indexers
// declare methods
// declare properties
}
Syntax for Implementing Interface:
class class_name : interface_name
To declare an interface, use interface keyword. It is used to provide total abstraction. That means all the members
in the interface are declared with the empty body and are public and abstract by default. A class that implements
interface must implement all the methods declared in the interface.
Example 1:
using System;
interface interface_exmp
{
void display();
}
class program : interface_exmp
{
public void display()
{
Console.WriteLine("Implementing Interface");
}
public static void Main (String []args)
{
program obj = new program();
obj.display();
}
}
Output:
Implementing Interface
Example 2
using System;
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
Output:
The pig says: wee wee
using System;
Example 3
interface Drawable
{
void draw();
}
// target method
static void MethodA(string message)
{
Console.WriteLine(message);
}
We can set the target method by assigning a method directly without creating an object of delegate
e.g., MyDelegate del = MethodA.
After setting a target method, a delegate can be invoked using the Invoke() method or using the () operator.
Example: Invoke a Delegate
del.Invoke("Hello World!");
// or
del("Hello World!");
The following is a simple example of a delegate.
Example 1: Delegate
using System;
public delegate void del_display();
class program
{
public void display()
{
Console.WriteLine("Invoking Delegates");
}
public static void Main(String []args)
{
program obj = new program();
del_display delobj = new del_display(obj.display);
delobj();
// we can write it like
// delobj.Invoke();
}
}
Output
Invoking Delegates
Example 2: Delegate
using System;
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
class program
{
public void sum(int a, int b)
{
Console.WriteLine("({0} + {1}) = {2}", a,b,a+b);
}
Output
(100 + 10) = 110
(100 - 10) = 90
Example 3: Delegate
using System;
delegate int Calculator(int n);//declaring delegate
Output:
After c1 delegate, Number is: 120
After c2 delegate, Number is: 360
Unit-3
C# Namespaces
Namespaces are used to organize the classes. It helps to control the scope of methods and classes in
larger .Net programming projects. In simpler words we can say that it provides a way to keep one set of names
(like class names) different from other sets of names.
The biggest advantage of using namespace is that the class names which are declared in one namespace will not
clash with the same class names declared in another namespace. It is also referred as named group of
classes having common features. The members of a namespace can be namespaces, interfaces, structures,
and delegates.
Defining a Namespace
To define a namespace in C#, we will use the namespace keyword followed by the name of the namespace and
curly braces containing the body of the namespace as follows:
Syntax:
namespace name_of_namespace
{
// Classes
// Interfaces
// Structures
// Delegates
}
Example:
namespace name1
{
// C1 is the class in the namespace name1
class C1
{
}
}
Accessing the Members of Namespace
The members of a namespace are accessed by using dot (.) operator. A class in C# is fully known by its respective
namespace.
Syntax:
[namespace_name].[member_name]
Note:
Two classes with the same name can be created inside 2 different namespaces in a single program.
Inside a namespace, no two classes can have the same name.
In C#, the full name of the class starts from its namespace name followed by dot (.) operator and the class
name, which is termed as the fully qualified name of the class.
Example:
using System;
namespace myspace
{
class firstclass
{
public static void display()
{
System.Console.WriteLine("Hello World!");
}
}
/* Removing comment will give the error
because no two classes can have the
same name under a single namespace
class firstclass
{
public static void display()
{
System.Console.WriteLine("Hello World!");
}
}
*/
}
class firstclass
{
public static void Main(String []args)
{
myspace.firstclass.display();
}
}
Output:
Hello World!
Example 2
using System;
namespace First
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello First Namespace");
}
}
}
namespace Second
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello Second Namespace");
}
}
}
public class TestNamespace
{
public static void Main()
{
First.Hello h1 = new First.Hello();
Second.Hello h2 = new Second.Hello();
h1.sayHello();
h2.sayHello();
}
}
Output
Hello First Namespace
Hello Second Namespace
Namespace: System
The System namespace contains fundamental classes and base classes that define commonly-used value and
reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
Classes
AccessViolationException The exception that is thrown when there is an attempt to read or write
protected memory.
ArgumentOutOfRangeException The exception that is thrown when the value of an argument is outside
the allowable range of values as defined by the invoked method.
AttributeUsageAttribute Specifies the usage of another attribute class. This class cannot be
inherited.
BadImageFormatException The exception that is thrown when the file image of a dynamic link
library (DLL) or an executable program is invalid.
BitConverter Converts base data types to an array of bytes, and an array of bytes to
base data types.
CharEnumerator Supports iterating over a String object and reading its individual
characters. This class cannot be inherited.
Console Represents the standard input, output, and error streams for console
applications. This class cannot be inherited.
C# Input output Classes
The System.IO namespace has various classes that are used for performing numerous operations with files, such as
creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace −
1
BinaryReader
Reads primitive data from a binary stream.
2
BinaryWriter
Writes primitive data in binary format.
3
BufferedStream
A temporary storage for a stream of bytes.
4
Directory
Helps in manipulating a directory structure.
5
DirectoryInfo
Used for performing operations on directories.
6
DriveInfo
Provides information for the drives.
7
File
Helps in manipulating files.
8
FileInfo
Used for performing operations on files.
9
FileStream
Used to read from and write to any location in a file.
10
MemoryStream
Used for random access to streamed data stored in memory.
11
Path
Performs operations on path information.
12
StreamReader
Used for reading characters from a byte stream.
13
StreamWriter
Is used for writing characters to a stream.
14
StringReader
Is used for reading from a string buffer.
15
StringWriter
Is used for writing into a string buffer.
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for
reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are two main streams:
the input stream and the output stream. The input stream is used for reading data from file (read operation) and
the output stream is used for writing into the file (write operation).
PROGRAMMING EXAMPLE
In this programming Example we will create a new file "CsharpFile.txt" and saves it on disk. And then we will
open this file, saves some text in it and then close this file.
CREATE A BLANK .TXT FILE USING FILESTREAM
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace FileStream_CreateFile
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Create);
fs.Close();
Console.Write("File has been created and the Path is D:\\csharpfile.txt");
Console.ReadKey();
}
}
}
Output
File has been created and the Path is D:\\csharpfile.txt
_
Explanation:
In the above program I added System.IO namespace so that I could use FileStream class in my program. Then I
created an object of FileStream class fs to create a new csharpfile.txt in D drive.
namespace AccessFile
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Append);
byte[] bdata=Encoding.Default.GetBytes("Hello File Handling!");
fs.Write(bdata, 0, bdata.Length);
fs.Close();
Console.WriteLine("Successfully saved file with data : Hello File Handling!");
Console.ReadKey();
}
}
}
Output
Successfully saved file with data : Hello File Handling!
_
Explanation
In the above program again I created object as fs of FileStrem class. Then Encoded a string into bytes and kept
into byte[] variable bdata and finally using Write() method of FileStream stored string into file.
namespace FileStream_ReadFile
{
class Program
{
static void Main(string[] args)
{
string data;
FileStream fsSource = new FileStream("D:\\csharpfile.txt", FileMode.Open, FileAccess.Read);
using (StreamReader sr = new StreamReader(fsSource))
{
data = sr.ReadToEnd();
}
Console.WriteLine(data);
Console.ReadLine();
}
}
}
Output
Hello File Handling!
C# Multithreading
Multitasking is the simultaneous execution of multiple tasks or processes over a certain time interval.
Windows operating system is an example of multitasking because it is capable of running more than one process at
a time like running Google Chrome, Notepad, VLC player, etc. at the same time. The operating system uses a term
known as a process to execute all these applications at the same time. A process is a part of an operating system
that is responsible for executing an application. Every program that executes on your system is a process and to run
the code inside the application a process uses a term known as a thread.
A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the
program. So every program has logic and a thread is responsible for executing this logic. Every program by default
carries one thread to execute the logic of the program and the thread is known as the Main Thread, so every
program or application is by default single-threaded model. This single-threaded model has a drawback. The
single thread runs all the process present in the program in synchronizing manner, means one after another. So, the
second process waits until the first process completes its execution, it consumes more time in processing.
For example, we have a class named as program and this class contains two different methods,
i.e method1, method2. Now the main thread is responsible for executing all these methods, so the main thread
executes all these methods one by one.
C# Thread class
C# Thread class provides properties and methods to create and control threads. It is found in System.Threading
namespace.
C# Thread Properties
A list of important properties of Thread class are given below:
Property Description
IsAlive checks whether the current thread is alive or not. It is used to find the
execution status of the thread.
C# Thread Methods
A list of important methods of Thread class are given below:
Method Description
ResetAbort() is used to cancel the Abort request for the current thread.
Sleep(Int32) is used to suspend the current thread for the specified milliseconds.
C# UriBuilder
UriBuilder provides a convenient way to modify the contents of a Uri instance without creating a new Uri instance
for each modification.
C# HttpWebRequest
HttpWebRequest is used to create an HTTP request. The resource is specified with the Uri.
C# hostname
The Dns.GetHostName method gets the host name of the local computer.
C# GetHostEntry
With the Dns.GetHostEntry method, we can determine an IP address from the hostname.
C# Ping
Ping is a network administration utility used to test the availability of a host on an Internet Protocol (IP) network.
Ping works by sending Internet Control Message Protocol (ICMP) echo request packets to the target host and waits
for an ICMP echo reply. The program reports errors, packet loss, and a statistical summary of the results.
.NET contains the Ping class for sending ping requests. The Ping class uses instances of the PingReply class to return
information about the operation and receive the reply.
C# Socket
In programming, a socket is an endpoint of a communication between two programs running on a network. Sockets
are used to create a connection between a client program and a server program.
Sockets in computer networks are used to establish a connection between two or more computers and used to send
data from one computer to another. Each computer in the network is called a node. Sockets use nodes’ IP addresses
and a network protocol to create a secure channel of communication and use this channel to transfer data.
Managing Console I/O Operations
To allow console input/output operations, C# provides, C# provides a console class. The Console class provides basic
input and output support for applications that read from and write characters to the console. The standard input,
output, and error streams are represented by properties, and are automatically associated with the console when the
application starts. Application can redirected these properties to other streams; for example, streams associated with
fies instead of the console.
By default, the read methods in console class use the standard input stream (keyboard) and the write methods use the
standard output (monitor) stream.
The write methods support writing data with or without automatically appending carriage return and linefeed
characters. This enables the writing of string, formatted strings, arrays of characters, instances of primitive types, and
arbitrary objects without first having to convert them to strings.
The following example demonstrates the use of basic Console input and output functions.
/* Console Input/Ouput */
using System;
class ConsoleTest
{
public static void Main()
{
Console.Write("Hello");
Console.WriteLine("World");
Console.Write("What is Your Name");
String name = Console.ReadLine();
Console.Write("Hello, ");
Console.Write(name);
Console.WriteLine(" ! ");
}
}
Console Class:
The methods for reading from and writing to the console are provided by the System. Console class. This class gives
us access to the standard input, standard output.
Console Input:
The console input stream object supports two methods for obtaining input from the keyboard.
1. Read(): It returns a single character as int.
Example:
int p=Console.Read();
Console.WriteLine((char)p);
C# - Error Handling
When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong
input, or other unforeseeable things.
When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will
throw an exception (throw an error).
C# Exception Classes
All the exception classes in C# are derived from System.Exception class. Let's see the list of C# common exception
classes.
Exception Description
System.FieldAccessException handles the error generated by invalid private or protected field access.
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.
try − A try block allows us to define a block of code to be tested for errors while it is being executed. It is
followed by one or more catch blocks.
catch − The catch keyword indicates the catching of an exception. When an exception occurs, the Catch
block of code is executed. This is where we are able to handle the exception, log it, or ignore it.
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 programmer throws an exception when a problem shows up. This is done using a throw keyword.
C# try and catch
The try statement allows us to define a block of code to be tested for errors while it is being executed.
The catch statement allows us to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs:
Syntax
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
Consider the following example, where we create an array of three integers:
This will generate an error, because myNumbers[10] does not exist.
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]); // error!
The error message will be something like this:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
If an error occurs, we can use try...catch to catch the error and execute some code to handle it.
In the following example, we use the variable inside the catch block (e) together with the built-in Message property,
which outputs a message that describes the exception:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
Output:
Index was outside the bounds of the array.
We can also output our own error message:
Example
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
Output:
Something went wrong.
Example 2
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter First number");
int num1 = Convert.ToInt32(Console.ReadLine());
}
}
}
Output:
Unhandled Exception:
System.DivideByZeroException: Attempted to divide by zero.
at HelloWorld.Program.Main (System.String[] args) [0x0002a] in
<b179e51f5ea24fe5bec684f8b3e11004>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide
by zero.
at HelloWorld.Program.Main (System.String[] args) [0x0002a] in
<b179e51f5ea24fe5bec684f8b3e11004>:0
}
}
}
Output:
Enter First number 10
Enter Second number 0
You can not divide a number by zero
Attempted to divide by zero.
10
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
}
}
}
Output:
Something went wrong.
The 'try catch' is finished.
class program
{
Console.WriteLine(Enter your Age :);
int age=Convert.ToInt32(Console.ReadLine());
try
if(age>=18)
else
catch (Exception e)
Console.WriteLine(e.Message);
}
The error message displayed in the program will be:
Output:
Enter your Age :
15
Windows Forms
Windows Forms is a Graphical User Interface (GUI) class library which is bundled in .Net Framework. Its main
purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs. It is also termed as
the WinForms. The applications which are developed by using Windows Forms or WinForms are known as
the Windows Forms Applications that runs on the desktop computer. WinForms can be used only to develop
the Windows Forms Applications not web applications. WinForms applications can contain the different type of
controls like labels, list boxes, tooltip etc.
Creating a Windows Forms Application Using Visual Studio 2017
First, open the Visual Studio then Go to File -> New -> Project to create a new project and then select the
language as Visual C# 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.
Here the solution is like a container which contains the projects and files that may be required by the program.
After that following window will display which will be divided into three parts as follows:
1. 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.
2. 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.
3. 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.
You can also reset the window layout by setting it to default. To set the default layout, go to Window -> Reset
Window Layout in Visual Studio Menu.
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.
Now drag and drop the controls that you needed on created Form. For example, if you can add TextBox, ListBox,
Button etc. as shown below. By clicking on the particular dropped control you can see and change its properties
present in the right most corner of Visual Studio.
In the above image, you can see the TextBox is selected and its properties like TextAlign, MaxLength etc. are
opened in right most corner. You can change its properties’ values as per the application need. The code of
controls will be automatically added in the background. You can check the Form1.Designer.cs file present in the
Solution Explorer Window.
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.
Unit-4
Web Services in C#
Introduction
Web Service is known as the software program. These services use the XML to exchange the information with the
other software with the help of the common internet Protocols. In the simple term, we use the Web Service to interact
with the objects over the internet. Web services are web application components. Web services can be published,
found, and used on the Web.
Here are some points about the Web Service.
1. Web Service is not dependent on any particular language.
2. Web Service is a protocol Independent.
3. Web Service is platform-independent.
4. Web Service is known as the Stateless Architecture. These services are dependent only on the given input.
5. Web Service is also Scalable.
6. Web Service is based on the XML (Open, Text-Based Standard).
MyService.asmx
<%@ WebService Language="C#" CodeBehind="MyService.asmx.cs"
Class="MyWebServiceDemo.MyService"%>
MyService.asmx.cs
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
// Use "Namespace" attribute with an unique name,to make service uniquely discoverable
[WebService(Namespace = "http://tempuri.org/")]
// To indicate service confirms to "WsiProfiles.BasicProfile1_1" standard,
// if not, it will throw compile time error.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To restrict this service from getting added as a custom tool to toolbox
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX
[System.Web.Script.Services.ScriptService]
public class MyService : WebService
{
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
}
}
Now, the service is ready to be used, let's compile and test it.
Test a web service
Let's run the project by hitting F5. The “http://localhost:56655/MyService.asmx” page will open that has a link for
the Service description (the WSDL document, documentation for web service) another link for SumOfNums, which
is for test page of SumOfNums method.
Let's use method overloading of the OOP concept. Add the following WebMethod in MyService class.
[WebMethod]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
Hit F5 to run the application, you will get “Both Single SumOfNums(Single, Single) and Int32 SumOfNums(Int32,
Int32) use the message name 'SumOfNums'. Use the MessageName property of the WebMethod custom attribute to
specify unique message names for the methods.” error message. We just used method overloading concept, so why
this error message? This is because these methods are not unique for a client application. As the error message
suggests let's use the MessageName property of the WebMethod attribute as shown below:
[WebMethod (MessageName = "SumOfFloats")]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
Now, compile and run the application. Again it's showing some different error message “Service
'MyWebServiceDemo.MyService' does not conform to WS-I Basic Profile v1.1”. As, WsiProfiles.BasicProfile1_1
doesn't support method overloading we are getting this exception. Now, either remove this
“[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]” attribute or make it
“[WebServiceBinding(ConformsTo = WsiProfiles.None)]”.
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : WebService
{
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
[WebMethod(MessageName = "SumOfFloats")]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
}
}
Now you can use method overloading in the service.
MyService.asmx
<%@ WebService Language="C#" CodeBehind="MyService.asmx.cs"
Class="MyWebServiceDemo.MyService" %>
MyService.asmx.cs
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService
{
// Takes 2 int values & returns their summation
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
Right-click on solution, select Add → New project then seelct ASP.NET Empty Application then name your
application, I am naming it “ServiceConsumer”.
Add a Web Form, I name it “Home.aspx”.
On the click of a button in this page, we will call our service.
For calling a Web Service you need a proxy object that will handle the complexities of sending a SOAP request and
response messages.
To create this proxy class, you need a reference to the service class. Right-click on this project then select Add
service reference, a window will open, type the URL of your service, click on discover, you will see all the
webmethods exposed by your service listed. At the bottom of the window, there'll be a field for Namespace. Provide
a name for the namespace in which the proxy class of the referenced service will be generated, I am giving it
“MyServiceReference”. Now, click on “Go”.
By adding a service reference, we created a proxy class of the referenced service to the current project (client app).
The proxy class wraps the calls to the web service's methods. It takes care of generating the correct SOAP message
format and managing the transmission of the messages over the network using HTTP and converting the results
received back to the corresponding .NET data types.
Now, add mark up in Home.aspx to receive inputs. Here's my mark up.
<table>
<tr>
<td>First Number:</td>
<td><input type="text" id="Text1" runat="server" /></td>
</tr>
<tr>
<td>Second Number:</td>
<td><input type="text" id="Text2" runat="server" /></td>
</tr>
<tr>
<td><input type="button" onserverclick="AddNumber" value="Add" runat="server" /></td>
<td><div id="divSum" runat="server"></div>
<div id="divSumThroughJson" runat="server"></div></td>
</tr>
</table>
Home.aspx.cs
using System;
using ServiceConsumer.MyServiceReference;
namespace ServiceConsumer
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void AddNumber(object Sender, EventArgs E)
{
int Num1, Num2;
int.TryParse(txtFirstNum.Value, out Num1);
int.TryParse(txtSecondNum.Value, out Num2);
// creating object of MyService proxy class
var ObjMyService = new MyServiceSoapClient();
$.ajax({
type: "POST",
url: "http://localhost/WebServiceForBlog/MyService.asmx/SumOfNums",
data: "First=" + FirstNum + "&Second=" + SecondNum,
// the data in form-encoded format, it would appear on a querystring
//contentType: "application/x-www-form-urlencoded; //charset=UTF-
8" //form encoding is the default one
dataType: "text",
crossDomain: true,
success: function (data) {
$('#divSum1').html(data);
}
});
The two properties that are of importance are the service name and the start type. While the former refers to the
name of the service that would be installed in our system, the second refers to how the service should be started.
There are three possible options for the start type of the service -- Automatic, Manual, and Disabled. All of these
start type options are self -- explanatory anyway.
Once done, all we would now need to do is compile the solution to create the executable file for the Windows service
we have implemented. Next, we should open the "Developer Command Prompt" of the version of Visual Studio
that is installed in our system and then use the command line utility named InstallUtil to install the service.
If the installation of the service is successful, we would see that the following messages (amongst other messages)
would be displayed in the console window, i.e., the Visual Studio Developer Command Prompt.
The Commit phase completed successfully.
The transacted install has completed.
Now, if the start type of our Windows service is set to "Manual", we should start our service manually. To do this,
go to Start -> Run and then type "Services.msc". When the "Services" window opens, locate our Windows service
and start it manually. This is all we need to do to build and execute our Windows service.
ASP.NET Web Forms
Web Forms are web pages built on the ASP.NET Technology. It executes on the server and generates output to the
browser. It is compatible to any browser to any language supported by .NET common language runtime. It is flexible
and allows us to create and add custom controls.
We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development Environment) that
allows us to drag and drop server controls to the web forms. It also allows us to set properties, events and methods for
the controls. To write business logic, we can choose any .NET language like: Visual Basic or Visual C#.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the form, which
resides in a separate class file.
• BorderWidth: This is used to set the width of the border of the label.
• Font: This is used to set the font for the label text.
• Text: This is used to set the text to be shown for the label.
• ToolTip: This displays the text when the mouse is over the label.
Example:
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
margin-left: 0px;
}
.auto-style3 {
width: 121px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Provide the Following Details:</h4>
<table class="auto-style1">
<tr>
<td class="auto-style3">
<asp:Label ID="lblName" runat="server" Text="User Name"></asp:Label></td>
<td>
<asp:TextBox ID="txtName" runat="server" CssClass="auto-style2"></asp:TextBox></td>
</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="lblFile" runat="server" Text="Upload a File"></asp:Label></td>
<td>
<asp:FileUpload ID="fileUploadId" runat="server" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
Text Box:
It is an input control, which is used to take user input. To create a Text Box you can either write code or use the drag
and drop facility web forms controls of visual studio IDE.
Syntax:
• ToolTip: This displays the text when mouse is over the control.
• MaxLength: This is used to set maximum number of characters that can be entered.
Example
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblName" runat="server">User Name</asp:Label>
<asp:TextBox ID="txtName" runat="server" ToolTip="Enter User Name"></asp:TextBox>
</div>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</p>
<br />
</form>
<asp:Label ID="lblInput" runat="server"></asp:Label>
</body>
</html>
Code Behind
// WebControls.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
lblInput.Text = lblName.Text;
Output:
It displays the user input when the user submits the input to the server.
List Box: It allows the selection of single as well as multiple items in the list, unlike the dropdown control, which
allows the selection of single item at a time.
Syntax:
• Items.Clear: It will clear all the selected items from the list box.
Example:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<div>
<h2>Choose a color:</h2>
<asp: ListBox ID ='lstColor’ runat = 'server' AutoPostBack = 'true' Font-Size = 'X-Large' Rows = '5'
</asp: ListBox>
</div>
</form>
</body>
</html>
Output:
Radio Button: Radio Button control is an input control that is used to takes input from the user. It allows the user to
select a choice from the group of choices.
Syntax:
• BorderWidth: This is used to set the width of the border of the control.
• Font: This is used to set the font for the control text.
• ForeColor: This is used to set the color of the control text.
• Text: This is used to set the text to be shown for the control.
• ToolTip: This displays the text when the mouse is over the control.
• GroupName: This is used to set the name of the radio button group.
Example:
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="submitGender" runat="server">
<div>
<asp:RadioButton ID="rdMale" runat="server" Text="Male" GroupName="gender" />
<asp:RadioButton ID="rdFemale" runat="server" Text="Female" GroupName="gender" />
</div>
<p>
<asp:Button ID="btnClick" runat="server" Text="Submit" OnClick="Button1_Click" style="width: 61px"
/>
</p>
</form>
<asp:Label runat="server" id="genderId"></asp:Label>
</body>
</html>
Code Behind
// WebControls.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
genderId.Text = "";
if (rdMale.Checked)
{
genderId.Text = "Your gender is "+rdMale.Text;
}
else genderId.Text = "Your gender is "+rdFemale.Text;
}
}
}
• BorderWidth: This is used to set the width of the border of the control.
• Font: This is used to set the font for the control text.
• Text: This is used to set the text to be shown for the control.
• ToolTip: This displays the text when the mouse is over the control.
• Checked: This is used to set check state of the control, either true or false.
Example:
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="submitCourse" runat="server">
<div>
<h2>Select Courses</h2>
<asp:CheckBox ID="chkJ2SE" runat="server" Text="J2SE" />
<asp:CheckBox ID="chkJ2EE" runat="server" Text="J2EE" />
<asp:CheckBox ID="chkSpring" runat="server" Text="Spring" />
</div>
<p>
<asp:Button ID="btnClick" runat="server" Text="Button" OnClick="Button1_Click" />
</p>
</form>
<p>
Courses Selected: <asp:Label runat="server" ID="ShowCourses"></asp:Label>
</p>
</body>
</html>
Code Behind
// WebControls.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowCourses.Text = "None";
}
protected void Button1_Click(object sender, EventArgs e)
{
var message = "" ;
if (chkJ2SE.Checked)
{
message = chkJ2SE.Text+" ";
}
if (chkJ2EE.Checked)
{
message += chkJ2EE.Text + " ";
}
if (chkSpring.Checked)
{
message += chkSpring.Text;
}
ShowCourses.Text = message;
}
}
}
Output:
After Selection
Button: Button control is used to perform events and is also used to submit client requests to the server.
Syntax:
• BorderWidth: This is used to set the width of the border of the control.
• Font: This is used to set the font for the control text.
• Text: This is used to set the text to be shown for the control.
• ToolTip: This displays the text when the mouse is over the control.
• Visible: This is used to set visibility of control on the form.
Example:
// WebControls.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="submitButton" runat="server">
<div>
<asp:Button ID="btnClick" runat="server" Text="Click here" OnClick="Button1_Click" />
</div>
</form>
<br />
<asp:Label ID="lblClick" runat="server"></asp:Label>
</body>
</html>
Code Behind
// WebControls.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
lblClick.Text = "You Clicked The Button.";
}
}
}
Output:
// EventHandling.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EnventHandling.aspx.cs"
Inherits="asp.netexample.EnventHandling" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 108px;
}
</style>
</head>
<body>
<form id="submitSum" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">First value</td>
<td>
<asp:TextBox ID="firstvalue" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Second value</td>
<td>
<asp:TextBox ID="secondvalue" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Sum</td>
<td>
<asp:TextBox ID="total" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td>
<br/>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"Text="Sum"/>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Code Behind
// EventHandling.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace asp.netexample
{
public partial class EnventHandling : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(firstvalue.Text);
int b = Convert.ToInt32(secondvalue.Text);
total.Text = (a + b).ToString();
}
}
}
Output:
ADO.NET
ADO.NET stands for ActiveX Data Object. It is a database access technology created by Microsoft as part of its
.NET framework that can access any kind of data source. ADO.NET provides a bridge between the front end
controls and the back end database.
The following are a few of the .NET applications that use ADO.NET to connect to a database, execute commands
and retrieve data from the database.
• ASP.NET Web Applications
• Console Applications
• Windows Applications.
Various Connection Architectures
There are the following two types of connection architectures:
1. Connected architecture: the application remains connected with the database throughout the processing.
2. Disconnected architecture: the application automatically connects/disconnects during the processing. The
application uses temporary data on the application side called a DataSet.
Understanding ADO.NET and its class library
In this diagram, we can see that there are various types of applications (Web Application, Console Application,
Windows Application and so on) that use ADO.NET to connect to databases (SQL Server, Oracle, OleDb, ODBC,
XML files and so on).
Important Classes in ADO.NET
We can also observe various classes in the preceding diagram. They are:
1. Connection Class
2. Command Class
3. DataReader Class
4. DataAdaptor Class
5. DataSet.Class
1. Connection Class
In ADO.NET, we use these connection classes to connect to the database. These connection classes also manage
transactions and connection pooling.
2. Command Class
The Command class provides methods for storing and executing SQL statements and Stored Procedures. The
following are the various commands that are executed by the Command Class.
• ExecuteReader: Returns data to the client as rows. This would typically be an SQL select statement or a
Stored Procedure that contains one or more select statements. This method returns a DataReader object that
can be used to fill a DataTable object or used directly for printing reports and so forth.
• ExecuteNonQuery: Executes a command that changes the data in the database, such as an update, delete, or
insert statement, or a Stored Procedure that contains one or more of these statements. This method returns an
integer that is the number of rows affected by the query.
• ExecuteScalar: This method only returns a single value. This kind of query returns a count of rows or a
calculated value.
• ExecuteXMLReader: (SqlClient classes only) Obtains data from an SQL Server 2000 database using an
XML stream. Returns an XML Reader object.
3. DataReader Class
The DataReader is used to retrieve data. It is used in conjunction with the Command class to execute an SQL Select
statement and then access the returned rows.
4. DataAdapter Class
The DataAdapter is used to connect DataSets to databases. The DataAdapter is most useful when using data-bound
controls in Windows Forms, but it can also be used to provide an easy way to manage the connection between your
application and the underlying database tables, views and Stored Procedures.
5. DataSet Class
The DataSet is the heart of ADO.NET. The DataSet is essentially a collection of DataTable objects. In turn each
object contains a collection of DataColumn and DataRow objects. The DataSet also contains a Relations collection
that can be used to define relations among Data Table Objects.
Advantages of ADO .NET
ADO.NET offers several advantages over previous Microsoft data access technologies, including ADO. The
following points will outline these advantages.
➢ Single Object- Oriented API
The ADO.NET provides a single object-oriented set of classes. There are different data providers to work with
different data sources, but the programming model for all these data providers to work in the same way. So if we
know how to work with one data provider, we can easily work with others. It’s just a matter of changing class names
and connection strings.
The ADO.NET classes are easy to use and to understand because of their object- oriented nature.
We can use more than one data provider to access a single data source. For example, we can use ODBC or OleDb
data providers to access Microsoft access databases.
➢ Managed Code
The ADO .NET classes are managed classes. They take all the advantages of .NET CLR, such as language
independency and automatic resource management. All .NET languages access the same API. So if you know how to
use these classes in C#, you’ll have no problem using them in VB.NET. Another big advantage is you don’t have to
worry about memory allocation and freeing it. The CLR will take care of it for you.
➢ Deployment
In real life, writing database application using ODBC, DAO, and other previous technologies and deploying on client
machines was a big problem was somewhat taken care in ADO except that three are different versions of MDAC.
Now we don’t have to worry about that. Installing distributable .NET components will take care of it.
➢ XML Support
Today, XML is an industry standard and the most widely used method of sharing data among applications over the
Internet. In ADO .NET data is cached and transferred in XML format. All components and applications can share this
data and we can transfer data via different protocols such as HTTP.
➢ Visual Data Components
Visual Studio .NET offers ADO .NET components and data– bound controls to work in visual form. That means we
can use these components as we use any windows controls. We drag and drop these components on windows and
web forms set their properties and write events. It helps programmers to write less code and develop applications in
no time. VS .NET also offers the data form wizard, which you can use to write full-fledged database applications
without writing a single line of code. Using these components you can directly bind these components with data-
bound controls by setting these control’s properties at design-time.
➢ Performance and Scalability
Performance and scalability are two major factors when developing web-based applications and services.
Transferring data one source to another is a costly affair over the Internet because of connection bandwidth
limitations and rapidly increasing traffic. Using disconnected cached data in XML takes care of both of these
problems.
➢ Connections and Disconnected data
With ADO .NET you use as few connections as possible and have more disconnected data. Both the ADO and ADO
.NET models support disconnected data but ADO’S record set object wasn’t actually designed to work with
disconnected data. So there are performance problems with that. However, ADO.NET’s dataset is specifically
designed to work with disconnected data and you can treat a dataset as a local copy of a database. In ADO.NET, you
store data in a dataset and close the make final changes to the data source. The ADO model is not flexible enough for
XML users; ADO uses OLE-DB persistence provider to support XML.
➢ DataReader versus DataSet
The ADO.NET DataReader is used to retrieve read-only (cannot update data back to a datasource) and forward-only
(cannot read backward/random) data from a database. You create a DataReader by calling Command.ExecuteReader
after creating an instance of the Command object.
➢ LINQ to DataSet
LINQ to DataSet API provides queries capabilities on a cached DataSet object using LINQ queries. The LINQ
queries are written in C#. Learn more here: LINQ to DataSet
➢ LINQ to SQL
LINQ to SQL API provides queries against relational databases without using a middle layer database library.
SqlDataAdapter.Fill()
It is used to retrieve the data from the database. Whenever we think that we need to get the data from any data source
in ADO.NET and fill this data into DataTable or DataSet, then we need to use objSqlDataAdapter.Fill(objDataSet);.
When we pass multiple select statement query to get the data, then it executes and gets one by one data and pass it to
corresponding tables.
So, first, we need to create a Stored Procedure to get the data from the database.
CREATE PROCEDURE GetEmployeeList
AS
BEGIN
SELECT * FROM dbo.Employees
END
Here we need to write our code on Employee.aspx.cs for getting the data.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace EmployeeDemo
if (!this.IsPostBack)
GetEmployeesList();
try
objSqlDataAdapter.Fill(dsEmployee);
dsEmployee.Tables[0].TableName = "Employees";
grvEmployee.DataSource = dsEmployee;
grvEmployee.DataBind();
return dsEmployee;
return dsEmployee;
} } }
Any object can be changed into a remote object by deriving it from MarshalByRefObject(Enables access to objects
across application domain boundaries in applications that support remoting). When a client activates a remote object,
it receives a proxy to the remote object. All operations on this proxy are appropriately indirected to enable
the Remoting infrastructure to intercept and forward the calls appropriately.
Using the .NET Framework to Develop Distributed Applications
The .NET Framework provides various mechanisms to support distributed application development. Most of this
functionality is present in the following three namespaces of the Framework Class Library (FCL):
• The System.Net Namespace—This namespace includes classes to create standalone listeners and custom
protocol handlers to start from scratch and create your own framework for developing a distributed application.
Working with the System.Net namespace directly requires a good understanding of network programming.
• The System.Runtime.Remoting Namespace—This namespace includes the classes that constitute the .NET
remoting framework. The .NET remoting framework allows communication between objects living in different
application domains, whether or not they are on the same computer. Remoting provides an abstraction over the
complex network programming and exposes a simple mechanism for inter-application domain communication.
The key objectives of .NET remoting are flexibility and extensibility.
• The System.Web.Services Namespace—This namespace includes the classes that constitutes the ASP.NET
Web services framework. ASP.NET Web services allow objects living in different application domains to
exchange messages through standard protocols such as HTTP and SOAP. ASP.NET Web services, when
compared to remoting, provide a much higher level of abstraction and simplicity. The key objectives of
ASP.NET Web services are the ease of use and interoperability with other systems.
Both .NET remoting and ASP.NET Web services provide a complete framework for designing distributed
applications. Most programmers will use either .NET remoting or ASP.NET Web services rather than build a
distributed programming framework from scratch with the System.Net namespace classes.
The functionality offered by .NET remoting and ASP.NET Web services appears very similar. In fact, ASP.NET
Web services are actually built on the .NET remoting infrastructure. It is also possible to use .NET remoting to design
Web services. Given the amount of similarity, how do you choose one over the other in your project? Simply put, the
decision depends on the type of application you want to create.
• .NET Remoting when both the end points (client and server) of a distributed application are in your control. This
might be a case when an application has been designed for use within a corporate network.
• ASP.NET Web services when one end point of a distributed application is not in your control. This might be a
case when your application is interoperating with your business partner's application.
Unsafe Code in C#
Before we start any discussion of Unsafe Code let us see an example.
int ab = 32;
int* p = &ab;
Console.ReadLine();
Console.WriteLine(*ptr);
++ptr;
Output
s
a
f
e
Writing unsafe code requires the use of the two special keywords unsafe and fixed. Now to understand the
meaning of both of those keywords.
Unsafe: The Unsafe keyword tells the compiler that this code will run in unsafe mode.
Fixed: We use fixed buffers inside an unsafe context. With a fixed buffer, we can write and read raw memory
without the managed overhead. Enter the fixed keyword. When used for a block of statements, it tells the CLR
that the object in question cannot be relocated.
How to run a program in unsafe mode
First go to the View tab.
Select the Solution Explorer option.
Expand the Solution Explorer a double-click on the Property option.
Now select the option of “Allow unsafe code” and mark it Check.
{
int var = 20;
int* p = &var;
Console.ReadKey();
Output
Example 2
Instead using the unsafe keyword for the Main function we can use it for a specific block of code, such as:
Unsafe
int* p = &var;
Console.ReadKey();
}
}
Output
The output will remain the same as above.
Example 3
In this program a function with the unsafe modifier is called from a normal function. This program shows that a
managed code can call unmanaged functions.
class Program
Unsafe();
Console.ReadKey();
int* p = &var;
Output
The output will the remain same as above.
Example 4
You can pass a pointer variable to a method as a parameter.
int* x = &var1;
int* y = &var2;
p.swap(x, y);
Console.ReadKey();
*p = *q;
*q = temp;
Output
Graphical Device Interface (GDI) In C#
The Graphics Device Interface (GDI) is responsible for representing graphical objects and transmitting them
to output devices such as monitors and printers.
GDI is responsible for tasks such as drawing lines and curves, rendering fonts and handling palettes.
GDI+ is the gateway to interact with graphics device interfaces in the .NET Framework. If you're going to write .NET
applications that interact with graphics devices such as monitors, printers, or files, you will have to use GDI+.
GDI+ is a library that provides an interface that allows programmers to write Windows and Web graphics
applications that interact with graphical devices such as printers, monitors, or files.
• System.Drawing
• System.Text
• System.Printing
• System.Internal
• System.Imaging
• System.Drawing2D
• System.Design
The Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object (for example circle or
rectangle) we have to create a surface using Graphics class. Generally we use Paint event of a Form to get
the reference of the graphics. Another way is to override OnPaint method.
Once you have the Graphics reference, you can call any of this class’s members to draw various objects.
Here are some of Graphics class’s methods:
Methods Description