C# and - Net Material1
C# and - Net Material1
NET
UNIT I
INTRODUCTION to C#: Introducing C#, Understanding .NET, Overview of C#, Literals,
Variables, Data Types, Operators, Expressions, Branching, Looping, Methods, Arrays, Strings,
Structures, Enumerations.
UNIT II
OBJECT ORIENTED ASPECTS OF C#: Classes, Objects, Inheritance, Polymorphism, Interfaces,
Operator Overloading, Delegates, Errors and Exceptions.
UNIT III
WINDOWS APPLICATIONS: Drawbacks of Console Applications, Container Controls, Non
Container Controls, Developing Windows Application from Notepad and Visual Studio, Events,
Types of Events – Mouse, Focus, Drag, Key and Other Related Events, Building Windows
Applications.
ADO.NET: Problems with File Handling, Data Source Communication, Drivers and Providers,
Introduction of ADO.NET, ADO.NET Namespaces, ADO.NET Objects, Accessing Data with
ADO.NET.
UNIT IV
BUILDING ASP.NET WEB PAGES: HTML form Development, Client side Scripting, Server side
Scripting, Web applications and Web servers, HTTP, Advantages Using ASP.NET, ASP.NET
Application, ASP.NET Namespaces, ASP.NET Web Page Structure, Creating Sample C# Web
Applications, ASP.NET Web Page Execution Architecture, Debugging and Tracing of ASP.NET.
UNIT V
ASP.NET WEB CONTROLS: Web Form Structures, Introduction to Web Form controls, Server
Side Controls, Web Server Controls, GET and POST, Page Submission, Web Page Creation
Techniques, Redirection between Web Pages, Validation Controls.
UNIT VI
WEB SERVICES: Web Services, Web Service Architecture, WSDL, Building WSDL Web Service.
CONFIGURING .NET ASSEMBLIES: Private Assemblies, Shared Assemblies, and Versioning.
MULTITHREADED PROGRAMMING: Thread Class, Life Cycle of a Thread, Steps for Creating
a Thread, Thread Synchronization.
UNIT I
.NET:
.NET stands for Network Enable Technology which is developed by Microsoft Corporation.
.NET is free, cross-platform,open source.
.NET is a collection of languages like VC#.NET, VC++.NET, VB.NET and so on.
.NET is a Framework which provides a common platform to Execute or Run the applications
developed in various programming languages.
.NET Objectives: The .NET Framework is designed to fulfil the following objectives
Platform independent: As .exe and .dll files work in any operating system with the help of
CLR, hence .Net is called as platform independent.
(.exe) is executable file, it consists of executable code, and (.dll) is dynamic link library file it
consist of reusable code. .exe and .dll files contains the code in the format of byte code is also
called as MSIL (Microsoft intermediate language) code.
Machine language is also called as native code. CLR is common language runtime; CLR
software converts byte code into native code. Dot Net is platform independent but CLR
software is platform dependent.
One question arises if we go in detail, that is either Dot Net is pure platform independent or
not? Answer is Dot Net is partially platform dependent, as of now CLR software's are not
available for DOS operating system and Windows 95.
Language independent: As Dot Net programming logic can be developed in any Dot Net
framework compatible languages; hence Dot Net is called as language independent.
Microsoft is introducing approximately 40 languages into Dot Net framework, out of which
as of now approximately 24 languages and one specification are released.
Ex: VC#.Net,VB.Net,VC+
+,VJ#,VF#,PHP,COBOL,PERL,PHYTHON,SMALLTALK,JSCRIPT...etc One specification
is ASP.Net.
Language interoperability: It is a concept of developing an application with the help of
more than one .NET programming language. After an application is compiled, the source
code will be converted into byte code. Byte code follows a standard instruction set provided
by cls(common language specification).Cls provides common rules and syntaxes for all the
languages and cls also provides common data types for all the languages and these common
data types are called as CTS(common type system).
C++ C# VB .NET
int(2) short(2) short(2)
long(4) int(4) integer(2)
long(8) long(8)
SYSTEM.INT16
SYSTEM.INT32
SYSTEM.INT64
It supports object-oriented programming environment.
It supports to work with database programming with the help of ADO.NET.
It supports to work with WPF (windows presentation foundation) for developing animations.
It Provides environment for developing various types of applications, such as Windows-
based applications and Web-based applications
It Supports to develop 3-tier architecture with the help of Dot Net remoting
Supports to develop game programming with the help of multi-threading
Supports to work with link programming
Dot Net remoting: It provide interface communication between application domine by using
Remoting Frame Mask.
Managed Code: The code is developed and running under the control of the CLR is often
termed managed code.
Unmanaged code: The code which takes OS help while execution is called as unmanaged code
Note: Managed code is faster in execution.
In simple words, a function ,class or anything written in one language can be easily used in another
language(c# to VB.NET).Therefore, impove the efficiency of the development process.
Interoperability:Any language code can use code written in any other language.
(or)
The ability of code to interact with code that is written that is written using different
programming language.
Language interoperability can help maximize code reverse
Every code written in any .NET language and compiled could be reversed by another .NET
languages.
os Unmanaged code
CLR
.net .dll Output
.exe
Managed code
.NET Framework:
The .Net framework is a revolutionary platform that helps you to write the following types of
applications:
Windows applications
Web applications
Web services
The .NET framework applications are multi-platform applications.
The .NET framework has been designed in such a way that it can be used by .NET
framework compatible languages ( C#, C++, Visual Basic, Jscript, COBOL, etc). All .NET
framework compatible languages can access the framework as well as communicate with
each other.
The .NET frame work contain three major things that is
Languages—VB,C#,PASCAL,COBOL
Technology—ASP.NET,ADO.NET
Servers—SQL SERVER,SHARE POINT SERVER
In platform independent languages, the code gets executed under the control of special
software called framework.
Example: java-->JVM
.NET-->CLR
Framework: A framework is a software which masks the functionalities of a OS and makes
the code to execute under its control .Frame work provides the following basic features like
Platform independency
Security
Memory management
Microsoft has started the development of .NET framework in late 90’s originally under the
name of NGWS (next generation windows services).
To develop the framework first the Microsoft has prepared a set of specifications known as
PLINQ TPL
A library is a set of reusable functionalities where each and every programming language has
built in library like header files in c/c++ ,packages in java similarly .NET languages have
built in libraries known as base class libraries .the speciality of these library is that they can
be consumed under any .NET language(BCL are the best example of language
interoperability because those library are developed in C# language and can be consumed in
any .NET framework compatible languages.
The very popular namespace in base class library is system
We can use the base class library in system namespace for many different tasks including.
Input/output operations
String handling
Managing arrays, lists and maps
Accessing files and file systems
Security
Windowing
Windows messages
Drawing
Database management
Managing errors and exceptions
Win form technology is used to develop windows based applications.
Asp.net is used to build rich internet based web applications
Ado.net is used to create Data Access Layer to query and manipulate data from underlying data
source like SQL Server, Oracle etc.
WPF (windows presentation foundation) is used to create applications with a rich user
experience. It includes application User Interface, 2D graphics, 3D graphics and multimedia. It
takes advantage of hardware acceleration of modern graphic cards. WPF makes the User
Interface faster, scalable and resolution independent.
WCF (windows communication foundation) is used for building and developing services based
on Web Services standards.
WF (WWF) stands windows workflow foundation, which is used to build process oriented
business workflow and rules engine. (validate business logic by multiple rules.)
LINQ (language integrated query) allows you to query(communicate) for the data from the
various data sources (like SQL databases, XML documents, Ado.Net Datasets, Various Web
services and any other objects such as Collections, Generics etc.) using a SQL Query like syntax
The C# principal designer and lead architect Anders Hejlsberg has previously involved with
the design of visual j++, Borland Delphi, Turbo Pascal languages.
The following reasons make C# a widely used professional language:
It is a modern, general-purpose programming language
It is object oriented.
It is component oriented.
It is easy to learn.
It is a structured language.
It produces efficient programs.
It can be compiled on a variety of computer platforms.
It is a part of .Net Framework.
OVERVIEW OF C#: C# can be used to develop two categories of programs, that is
Executable application programs: These programs are written to carry out certain tasks and
require the main method in one of the classes.
Component libraries: These do not require a main declaration because they are not stand-
alone application programs. These are written for use by other applications.
CHARACTERISTICS OF C#:
SIMPLE:
1. C# is simple by eliminating some operators such as "::” or "->" and pointers.
2. C# treats integer and Boolean data types as entirely two different data types. Boolean values
are pure true or false values in C# so no more errors of "="operator and "=="operator."==" is
used for comparison operation and "=" is used for assignment operation.
MODERN: C# is a modern language because of the following features.
1. It provides Automatic garbage collection.
2. It provides Rich intrinsic model for error handling.
3. It provides Modern approach to debugging
4. It provides robust security model.
5. It provides Decimal data type for financial applications.
OBJECT ORIENTED:
1. C# truly object oriented. It supports Data Encapsulation, inheritance, polymorphism,
interfaces.
2. In C#, everything is an object .there are no more global functions, variables and constants.
TYPE SAFE:
Applications of C#:
Console applications
Windows applications
Developing windows controls
Developing ASP.NET projects
Creating web controls
Providing web services
Developing .NET component library
NOTES:
C# is case sensitive.
All statements and expression must end with a semicolon (;).
The program execution starts at the Main method.
Unlike Java, program file name could be different from the class name.
CREATING A SIMPLE C# PROGRAM: A simple code that prints the words "Hello World":
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
Output: Hello World
using System:
using System:
using is the keyword, which is used to specify namespace.
The above line tells the compiler to look into the System namespace library for unresolved
class names.
Because of the above line we have not used system prefix to the console class in the output
line.
When the compiler parses the Console.WriteLine method, it will understand that the method
is undefined, However it will search through the namespaces specified in using directives and
upon finding the method in the system namespace ,will compile the code without any
complaint.
Namespace declaration: A namespace is a collection of classes. The HelloWorldApplication
namespace contains the class Hello World.
Class Declaration: The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple methods. Methods
define the behaviour of the class. However, the HelloWorld class has only one method Main. The
line
class Helloworld:
The above line Declares a class, C# is true object oriented language and therefore everything
must be placed inside a class.
Class is keyword, which declares new class definition.
Helloworld is the name of the class. It should be a valid identifier.
Braces({ }):C# is a block structured language and the code always enclosed by { and }.therefore
every class definition in c# begins with opening brace { and ends with a closing brace }.
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
Output: Length: 4.5 Width: 3.5 Area: 15.75
USING ALIASES FOR NAMESPACE CLASSES: we have seen how we can avoid the prefix
System to the Console class by implementing the using System; statement. can use this approach to
avoid prefixing of System.Console to the method WriteLine() ? The answer is no.
System is a namespace and Console is a class. The using directive can be applied only to
the namespaces and cannot be applied to classes. Therefore the statement
using System.Console;
The above statement is illegal. However, we can overcome this problem by using aliases for
namespace classes. This takes the following form.
using aliasname=classname;
Example: using A= System.Console; //A is alias for System.Console
class sample
{
pubic static void Main()
{
A.WriteLine(“Hello”);
}
}
PASSING STRING OBJECTS TO WRITELINE METHOD: So far we have seen constant string
output to the Console. we can store string values in string objects and use these objects as parameters
to the WriteLine method. We can use string data type to create string variable and assign string
constant to it.
string s=”abc”;
The content of s may be printed out using the WriteLine method.
System.Console.WriteLine(s);
Example: using System;
class sample
{
class static void Main()
{
string name=”c sharp”;
Console.WriteLine(name);
}
}
COMMAND LINE ARGUMENTS: command line arguments are parameters supplied to the Main
method at the time of invoking it for execution.
Output: hello
C sharp
MAIN WITH A CLASS:
Example: class testclass
{
public void fun()
{
System.Console.WriteLine(“C# is simple”);
}
}
class sample
{
public static void Main()
{
testclass test= new testclass(); // creating test object
test.fun(); // calling fun() function
}
}
The above program has two class declarations, one for the testclass and another for the Main
method.testclass contains only one method to print a string “C# is simple”.The Main method
in simple class creates an object of testclass and uses it to invoke the method fun() contained
in testclass.
The object test is used to invoke the method fun() of testclass with the help of the dot
operator.
PROVIDING INTERACTIVE INPUT: So far we have seen two approaches for giving values to
string objects.
Using an assignment statement.
Through command line arguments.
It is possible to give values to string variables interactively through the keyboard at the time of
execution.
name. The moment the user types his name and presses the enter key, the input is read into the string
variable name. The second output line “Console.WriteLine(“Hello”+name);” concatenates the
name-string with hello and presents the resultant string to the user.
Output: enter your name raja
Hello raja
Example1: using System;
class sample
{
public static void Main()
{
Console.WriteLine(“what is your name”);
string s=Console.ReadLine();
Console.WriteLine(“Hello”+s);
Console.WriteLine(“what is your age”);
string s=Console.ReadLine();
Console.WriteLine(“you look nice at”+s);
}
}
TOKENS: The smallest, non-reducible, textual elements in a program are referred to as tokens.
The compiler recognizes them for building up expressions and statements. A C# program is a
collection of tokens, comments and whitespaces. The c# tokens are
Keywords
Identifiers
Literals
Operators
Punctuators
KEYWORDS: Keywords are reserved words which are, predefined to the C# compiler. They have
fixed meanings and these meanings cannot be changed. Keywords serve as basic building blocks for
program statements. All keywords must be written in lowercase. Keywords cannot be used as
identifiers except when they are prefaced by the @ character.
In C#, some identifiers have special meaning in context of code, such as get and set, these are called
contextual keywords.
integer. It may also include alphabets A through F (or) a through f.A letter A through F represents the
numbers from 10 through 15.
Examples: Valid examples Invalid examples
1. 0x2 1.0xnmjk
2. 0x87665 2.0x1286m
3. 0xabc 3.08972
4. 0x53647 4.0khjdi
Real literals: The numbers containing fractional part is called real (or) floating-point literals. We
have two Notations for representing real literals.
Decimal notation
Scientific notation (or) exponential notation
Decimal notation: It represents numbers having a whole number followed by decimal point and
fractional part.
Example: 215.
.95
-.75
+.5
Scientific notation: A real number may also be expressed in exponential (or) scientific notation.
Example: The number 215.65 may be written as 2.1565e2 in exponential notation.e2 means multiply
by 102.
Syntax: mantissa e exponent
Mantissa: mantissa is either a real number expressed in decimal notation.
Exponent: It is an integer number with an optional sign.
E (or) e: It separates the mantissa and the exponent can be written in either uppercase (or) lower
case.
Example: 0.65e4
12e-2
1.5e+5
3.18e3
Exponential notation is useful for representing the numbers that are either very large (or) very
small in magnitude.
Example: 7500000000 is equals to 7.5e9 is also equals to 75e8
-0.000000368 is equals to -3.68e-7
Boolean literals: There are two Boolean literal values
true
false
Character literals:
Single Character Constants: A single character constant contains a single character enclosed by
single quote marks is called single character constants.
Examples: ‘a’
22 School of Computer Science & Engineering | RGMCET
C# AND .NET
’#’
’2’
’’
String Constants: A string constant is a sequence of characters enclosed by double quotes. The
character may be any letter, digits, special characters and blank space .
Example: “Welcome to c programming”
“2001”
“Well done”
“34+23”
“d”
BACKSLASH CHARACTER CONSTANTS: C# supports some special backslash character
constants that are used in output methods. Each backslash character constant contains two
characters to represent a single character. These combinations are called escape sequences.
1. \a – alert
2. \b – Backspace
3. \f – Form feed
4. \n – New line
5. \r – Carriage return
6. \t – Horizontal tab
7. \v – Vertical tab
8. \\ – Backslash
9. \' – Single quote
10. \" – Double quote
11. \0 - Null
DATA TYPES: Every variable in C# is associated with a data type.Data types specify the type and
size of values that a variable can be stored. The data types in C# are primarily divided into two
types.:
Value types
Reference types
Value types and reference types differ in two characteristics:
Where they are stored in the memory
How they behave in the context of assignment statements.
Value Type: Value types (which are of fixed length) are stored on the stack(stack is a place where
the data stores in fixed length like float,int etc.), when a value of a variable is assigned to a variable
the value is actually copied. This means that two identical copies of the value are available in
memory.
The value types of C# can be grouped into two categories, namely,
User defined types (or) complex types
Predefined types (or) simple types
User defined types (or) complex types: Here we can define our own complex types by using
predefined types known as User defined value types, which includes
structures
enumerations
Predefined types: These are also known as simple types (or) primitive types. Predefined types are
divided into
Numeric types
Boolean types
Character types
Numeric types: Numeric types include integral types, floating point types and decimal types.
Subtypes:
1. Integer
2. Float
3. decimal
Integral types: Integral types can hold whole numbers such as 123, -96 and 5639.The size of the
values that can be stored depends on the integral data type we choose. C# supports the concept of
signed and unsigned types and therefore it supports eight types of integers .
Signed integers: signed integer types can hold both positive and negative numbers.
Type Size Minimum value Maximum value
sbyte 1 byte -128 +127
short 2 byte -32768 +32767
int 4 byte 2147483648 +2147483647
long 8 byte -9223372036854775808 +9223372036854775807
Unsigned integers: unsigned integer types can hold only positive numbers
Type Size Minimum value Maximum value
byte 1 byte 0 255
ushort 2 byte 0 65535
uint 4 byte 0 4294967295
ulong 8 byte 0 18446744073709551615
All integers are by default int type. In order to specify other integer types, we must append the
characters U,L or UL
123U(for uint type)
123L(for long type)
123UL(for ulong type)
Floating point types: Floating point types hold numbers containing fractional parts such as 27.59
and -1.375.There are two kinds of Floating point storage in C#
The Floating point values are single-precision numbers with a precision of seven digits.
The double types represent double-precision numbers with a precision of 15/16 digits
Type Size Minimum value Maximum value
float 4 byte 1.5x10-45 3.4x1038
double 8 byte 5.0x10-324 1.7x10308
Floating point numbers by default as double-precision quantities.to force them to be in single
precision mode, we must append f (or) F to the numbers.
Example: 1.23f
7.56923f
Double-precision types are used when we need greater precision in storage of floating-point
numbers.
Floating-point data types support a special value known as Not-a-Number(NaN).NaN is used to
represent the result of operations such as dividing zero by zero,where an actual number is not
produced. Most operations NaN as an operand will produce NaN as result.
Decimal type: The decimal type is a high precision,128-bit data type that is designed for use in
financial monetary calculations. It can store values in the range 1.0x10 -28 to 7.9x1028 with 28
significant digits.
To specify a number to be decimal type, we must append the character M or mto the value.
Example: 123.45M (if we omit M, the value will be treated as double).
Character type: In order to store single characters in memory, C# provides a character data type
called char. The char type assumes a size of two bytes but, in fact it can hold only a single character.
char data type has been designed to hold a 16-bit Unicode character, in which 8-bit ASCII code is a
subset.
Boolean type: Boolean condition can be used when we want to test a particular condition during the
execution of the program. There are two values that a Boolean type can take true (or) false. Boolean
type can be denoted by the keyword bool and uses only one bit of storage.
Reference types: reference types (which are of variable length) are stored on the heap, and when an
assignment between two reference variables occurs, only the reference is copied. The actual values
remains in the same memory location. This means there are two references to a single value. The
reference types can be divided into two groups
User defined types (or) complex types
Predefined types (or) simple types
User defined types: user defined reference types refer to those types which we define using
predefined type. They include
Classes
Delegates
Interfaces
25 School of Computer Science & Engineering | RGMCET
C# AND .NET
Arrays
Predefined types: Predefined types include two types
Object type
String type
VARIABLES: A variable is an identifier that denotes a storage location uses to store a data value. A
variable may take different values at different times during the execution of the program. Every
variable has a type that determines what values can be stored in the variable.
Rules for forming a variable:
They must not begin with a digit.
Uppercase and lower case is distinct. This means that the variable TOTAL is not same as total
or Total.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length.
Variable declaration: After designing suitable variable names, we must declare the variable before
it used in the program. Declaration does three things
It tells the compiler what the variable name is.
It specifies what type of data the variable will hold.
The place of declaration in the program decides the scope of the variable.
Syntax: data_type variable1, variable2,……. variableN;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined
data type, and variables are separated by commas. Some valid variable definitions are shown here:
int i, j, count;
float f, salary;
double pi;
byte b;
char c1,c2,c3;
decimal d1,d2;
uint m;
ulong n;
Initializing Variables: The process of giving initial values to the variables is called initialization.
Once the declaration has been done then initializes the variables with the assignment operator. The
general form of initialization is:
Syntax: variable_name = value;
It is also possible to assign a value at the time of its declaration.
Syntax: <data_type> <variable_name> = value;
Example:
int d = 3, f = 5;
byte z = 22;
double pi = 3.14159;
char x = 'x';
Example:
float x,y,z; //declares three variables
int m=5,n=10; //declares and initializes two int variables
int m, n=10; //declares m and n and initializes n.
Example: The following example uses various types of variables:
using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a; int b ; double c;
/* actual initialization */
a = 10; b = 20; c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
Output: a = 10, b = 20, c = 30
Scope of variables: The scope of the variable determines over what part(s) of the program a variable
is actually available for use (active).This depends on the type of the variable and place of its
declaration. C# defines several categories of variables.
Static variables
Instance variables
Array elements
Value parameters
Reference parameters
Output parameters
Local variables
Example: class ABC
{
static int m;
int n;
void fun (int x , ref int y, out int z, int[] a)
{
int j = 10;
}
}
m = static variable,
n = instance variable,
x = value parameter,
y = reference parameter,
j = local variable,
z =output parameter,
a[0] = array element
TYPE CONVERSION: The process of converting one data type into another data type is known as
type casting or type conversion. Type conversions are divided into two types.
1. Implicit (or) up casting (or) widening (or) automatic type conversion.
2. Explicit (or) down casting (or) narrowing type conversion.
Implicit type conversion (Automatic type conversion): Converting lower data type into higher
data type is called widening. In this one data type is automatically converted into another type as per
the rules described in c# language, which means the lower level data type is converted automatically
into higher level data type before the operation proceeds. The result of the data type having higher
level data type.
Example: byte x = 12;
int y = x;
In the above statement, the conversion of data from byte to int is done implicitly, in other words
programmers don’t need to specify any type operators. Widening is safe because there will not be
any loss of data. This is the reason even though the programmer does not use the cast operator the
compiler does not complaint because of lower data type is converting into higher data type. Here
higher data type having the much more space to store the lower data type.
Example: using System;
namespace explicit_cast_conversion
{
class Program
{
static void Main(string[] args)
{
int num1=10;
long num2=num1;
Console.WriteLine("num2 value is : " +num2);
Console.ReadLine();
}
}
}
Explicit type conversion: Converting higher data type into lower data type is called narrowing.
Here we can place intended data type in front of the variable to be cast.
Syntax: data-type variablename1=(cast-type)variablename2;
Example: double d=12.67853;
int n = (int) d;
Here we are converting higher level data type into lower level data type that means double type is
converted into int type, the fractional part of the number is lost and only 12 is stored in n. Here we
are losing some digits this is the reason the compiler forces the programmer to use the cast operator
when going for explicit casting.
Example: using System;
namespace convert_conversion
{
class Program
{
static void Main(string[] args)
{
Convert.ToSingle(“3.14”);
Convert.ToSingle(“3.14”);
Convert.ToSingle(“3.14”);
Console.WriteLine(“Convert.ToSingle(“3.14”));
Console.ReadLine();
}
}
}
BOXING AND UNBOXING: In object oriented programming, methods are invoked using objects.
Since value types such as int and long are not objects, we cannot use them to call methods. C#
enables us to achieve this through a technique known as boxing.
Boxing: Boxing is the process of converting a value type to the reference type.
Boxing is an implicit type casting. To work with boxing, we required a predefined data type called
object. Object data type is capable to hold any type of data.
Example: int m=10;
object om=m; //Boxing
The first line we created a Value Type m and assigned a value to m. The second line, we created an
instance of Object om and assign the value of m to om. From the above operation, we saw converting
a value of a Value Type into a value of a corresponding Reference Type. This type of operation is
called Boxing.
We can also use a c-style cast for boxing.
int m=10;
object om=(object)m; // c-style casting
Note that the boxing operation creates a copy of the value of the m integer to the object om. Now
both the variables m and om exist but the value of om resides on the heap. This means that the values
are independent of each other. Consider the following code
int m=10;
object om=m;
m=20;
Console.WriteLine(m); //m=20
Console.WriteLine(om); //om=10
When a code changes the value of m, the value of om not affected.
Unboxing: Unboxing is the process of converting a reference type to value type. Remember that we
can only unbox a variable that has previously been boxed. Unboxing is an explicit type conversion.
When unboxing a value, we have to ensure that the value type is large enough to hold the
value of the object (reference type value). Otherwise, the operation may result in runtime error.
Example: int m=10;
object om=m;
byte n=(byte)om;
The above code will produce a runtime error.
Notice that when unboxing, we need to use explicit cast. This is because in case of unboxing, an
object could be cast to any type. Therefore, the cast operator is necessary for the compiler to verify
that it is valid as per the specified value type.
Example: int m = 10;
Object om = m; //Boxing
int i = (int)om; //Unboxing
The first two lines show how to Box a Value Type. The next line (int i = (int) om) shows extracts the
Value Type from the Object (reference type) . That is converting a value of a Reference Type into a
value of a Value Type. This operation is called Unboxing.
A c-style cast for unboxing
int m=10;
object om=m;
int n=(int)om;
Example: using System;
namespace boxing
{
class Program
{
static void Main(string[] args)
{
int i = 10;
object a = i; // boxing
int j = (int)a; // unboxing
Console.WriteLine("value of o object : " + a);
Console.WriteLine("Value of j : " + j);
Console.ReadLine();
}
}
}
OPERATORS: An operator is a symbol that tells the computer to perform specific mathematical or
logical manipulations. Operators are used in programs to manipulate data and variables. C# has rich
set of operators. C# operators can be classified into the following types:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
33 School of Computer Science & Engineering | RGMCET
C# AND .NET
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
Output: Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational Operators: These operators are used to compare the value of two variables. Relational
operator’s checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0.Assume variable A holds 10 and variable B holds
20, then:
Operator Meaning Description Example
> Greater than Checks if the value of left operand is greater than (a>b) is
the value of right operand, if yes then condition not true
becomes true.
< Less than Checks if the value of left operand is less than (a<b) is
the value of right operand, if yes then condition true
becomes true.
<= Less than or equals to Checks if the value of left operand is less than or a<=b is
equal to the value of right operand, if yes then true
condition becomes true.
>= Greater than or equals to Checks if the value of left operand is greater than a>=b is
or equal to the value of right operand, if yes then not true
condition becomes true.
!= Not equals to Checks if the values of two operands are equal or a!=b is
not, if values are not equal then condition true
becomes true.
35 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = true;
if (a && b)
Console.WriteLine("Line 1 - Condition is true");
if (a || b)
Console.WriteLine("Line 2 - Condition is true");
/* lets change the value of a and b */
a = false;
b = true;
if (a && b)
Console.WriteLine("Line3-Condition is true");
else
Console.WriteLine("Line3-not true");
if (!(a && b))
Console.WriteLine("Line4-Condition is true");
Console.ReadLine();
}
}
}
Output: Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Assignment Operators: These are used to assign the values for the variables in C# programs. The
most common assignment operator is =.The syntax is shown below:
data type Variable_name = expression;
{
static void Main(string[] args)
{
int a = 21;
int c;
c = a;
Console.WriteLine("Line 1 - =Value of c = {0}", c);
c += a;
Console.WriteLine("Line 2 - += Value of c = {0}", c);
c -= a;
Console.WriteLine("Line 3 - -=Value of c = {0}", c);
c *= a;
Console.WriteLine("Line 4 - *=Value of c = {0}", c);
c /= a;
Console.WriteLine("Line 5 - /=Value of c = {0}", c);
c = 200;
c %= a;
Console.WriteLine("Line 6 - %=Value of c = {0}", c);
Console.ReadLine();
}
}
}
Output: Line 1 - =Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c = 441
Line 5 - /= Value of c = 21
Line 6 - %= Value of c = 11
Increment/Decrement Operators: Increment operators are used to increase the value of the variable
by one and decrement operators are used to decrease the value of the variable by one in C programs.
Increment Operators:
1. ++ is an increment operator. This is an unary operator.
2. It increments the value of the operand by one.
Syntax: Incrementoperator: ++var_name; (or) var_name++;
Post Increment:If the increment operator ++ is placed after the operand, then operator is called Post
Increment. As the name indicates Post indicates means increment after the operand value is used.
Pre Increment:If the increment operator ++ is placed before the operand. Then operator is called
Pre Increment. As the name indicates Pre indicates, increment before the operand value is used.
Decrement Operators:
-- is a decrement operator. This is an unary operator.
It decrements the value of the operand by one.
The decrement operator is classified into two categories:
Post Decrement(Ex: a--) :If the decrement operator -- is placed after the operand. Then the operator
is called post decrement. So the operand value is used first and then the operand value is
decremented by 1.
Pre Decrement(Ex:--a) : If the decrement operator -- is placed before the operand then the
operator is called Pre decrement. So the operand value is decrement by 1 first and this
decremented value is used.
Example: using System;
class Program
{
static void Main(string[] args)
{
int i = 4;
i++;
Console.WriteLine(i);
++i;
Console.WriteLine(i);
i--;
Console.WriteLine(i);
--i;
Console.WriteLine(i);
}
}
Example: using System;
class Program
{
static void Main(string[] args)
{
int i = 4;int y = 0;
y = i++;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
Console.WriteLine();
++i;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
Console.WriteLine();
y = i--;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
Console.WriteLine();
y = --i;
Console.WriteLine("i = " + i);
Console.WriteLine("y = " + y);
}
}
Conditional Operators:The conditional operator is also called a ternary operator. As the name
indicates an operator that operates on three operands is called ternary operator.The ternary operators
consisting two symbols i.e ? and :
39 School of Computer Science & Engineering | RGMCET
C# AND .NET
Miscellaneous Operators: There are few other important operators including sizeof, typeof and ? :
supported by C#.
Value of b is 20
}
}
Output: a is not less than 20;
value of a is : 100
if...else if...else Statement: It is also called as multi-way decision statement .In this the conditions
are evaluated from top to downwards, when the true condition is found, the statements associated
with it is executed. When all the n conditions become false, then the final contains default statement
will be executed.
Syntax: if(boolean_expression 1)
Statement-1;
else if( boolean_expression 2)
Statement-2;
else if( boolean_expression 3)
Statement-n;
else
Default-Statement;
Example: using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 100;
if (a == 10)
Console.WriteLine("Value of a is 10");
else if (a == 20)
Console.WriteLine("Value of a is 20");
else if (a == 30)
Console.WriteLine("Value of a is 30");
else
Console.WriteLine("None of the values is matching");
Console.WriteLine("Exact value of a is: {0}", a);
Console.ReadLine();
}
}
}
Output: None of the values is matching
Exact value of a is: 100
Example: using System;
namespace if_else_construct
{
class Program
{
static void Main(string[] args)
{
int opt, num1, num2;
float result;
44 School of Computer Science & Engineering | RGMCET
C# AND .NET
label:
Console.WriteLine("\n\tMenu");
Console.WriteLine("\nPress 1 for add");
Console.WriteLine("Press 2 for subtraction");
Console.WriteLine("Press 3 for multiplication");
Console.WriteLine("Press 4 for Division");
Console.Write("\n\nEnter first number:\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number:\t");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nEnter your option:\t");
opt = Convert.ToInt32(Console.ReadLine());
if (opt == 1)
{
result = num1 + num2;
Console.WriteLine("\n{0}+{1}={2}",num1,
num2, result);
}
else if (opt == 2)
{
result = num1 - num2;
Console.Write("\n{0}-{1}={2}",num1,num2, result);
}
else if (opt == 3)
{
result = num1 * num2;
Console.Write("\n{0}x{1}={2}",num1, num2, result);
}
else if (opt == 4)
{
result = (float)(num1 / num2);
Console.Write("\n{0} / {1}={2}", num1, num2, result);
}
else
{
Console.WriteLine("Invalid option. Try again");
goto label;
}
Console.ReadLine();
}
}
}
Example: using System;
class BiggestNumber
{
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
45 School of Computer Science & Engineering | RGMCET
C# AND .NET
Example: The program finds greatest of three numbers and then prints the number which is
the greatest. If all 3 input numbers are same then it prints "Entered Numbers are not
Distinct.".
using System;
namespace DotNetMirror
{
class GreatestOfThreeNumbers
{
static void Main()
{
int number1, number2, number3;
Console.Write("Enter three numbers (followed by Enter key): ");
number1 = Convert.ToInt16(Console.ReadLine());
number2 = Convert.ToInt16(Console.ReadLine());
number3 = Convert.ToInt16(Console.ReadLine());
if (number1 > number2 && number1 > number3)
{
Console.Write("Number {0} is largest.", number1);
}
else if (number2 > number1 && number2 > number3)
{
Console.Write("Number {0} is largest.", number2);
}
else if (number3 > number1 && number3 > number2)
{
Console.Write("Number {0} is largest.", number3);
}
else
{
Console.Write("Entered Numbers are not Distinct.");
}
46 School of Computer Science & Engineering | RGMCET
C# AND .NET
Console.ReadLine();
}
}
}
Nested if Statements: The statements within the if statement can contain another if statement and
which in turn may contain another if and so on is called nested if-else statement. The nested if
statement is used when multiple conditions needs to be tested. The inner statement will execute only
when outer if statement is true otherwise control won't even reach inner if statement
Syntax: if( boolean_expression1)
{
if(boolean_expression2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Example: using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 100;
int b = 200;
if (a == 100)
{
if (b == 200)
Console.WriteLine("Value of a is 100 and b is 200");
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
Output: Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
}
else
{
Console.WriteLine("already an adult.");
}
}
else
{
Console.WriteLine("You are still too young.");
}
}
}
}
Switch Statement: A switch statement allows a variable or value of an expression to be tested for
equality against a list of possible case values and when match is found, the block of code associated
with that case is executed. Otherwise default case is executed.
break;
case constant2: Statements_lock2;
break;
default: default_block
}
The expression is evaluated first.
The value of the expression is compared against the constants, constant1, constant2…If a
case is found whose value matches the value of the expression, then the block of statements
that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and causes
an exit from the switch statement, transferring the control to the statements following the
switch.
The default is an optional case. when present, it will be executed if the value of the
expression does not match any of the case values. If not present, no action takes place when
all matches fail and the control goes to the statements following the switch
Flow Diagram
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
Output: Well done
Your grade is B
Example: using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 100;int b = 200;
switch (a)
{
case 100:Console.WriteLine("This is part of outer switch ");
switch (b)
{
case 200:Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
Output: This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
CONDITIONAL LOOPING: Loop control statements are used to execute a block of code several
times until the given condition is true
Or
The looping control statements that enable the programmer to execute a set of statements repeatedly
till the required activity is completed are called looping control statements
TYPES OF LOOPING CONTROL STATEMENTS: The looping control statements are divided
into two types. They are
Entry controlled loop: In such type of loop, the test condition is checked first before the loop is
executed. Examples of Entry controlled loop are: for and while.
Exit controlled loop: In such type of loop, the loop is executed first, then condition is checked, the
loop executed at least one time even the condition if false. Examples of exit controlled loop is do-
while.
For Loop: Repeats a block of code multiple times until a given condition is true. Initialization,
looping condition and update expression (increment/decrement) is part of for loop.
Syntax: for ( initialization; condition; increment/decrement )
{
statement(s);
}
Here is the flow of control in a for loop:
The initialization is usually an assignment statement that sets the loop control variable. For
Example: i=1 and count=0 Here i, count are loop control variables
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after
the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again testing for a condition). After the
condition becomes false, the for loop terminates.
int i,j;
i=0;
j=0;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
Console.Write(i);
}
Console.Write("\n");
}
Console.ReadLine();
}
}
}
Example: using System;
namespace nested_loop
{
class Program
{
static void Main(string[] args)
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++) //Nested for loop
{
Console.Write(j);
}
Console.Write("\n");
}
Console.ReadLine();
}
}
}
While Loop: A while loop repeats a statement or group of statements until a given condition is true.
It tests the condition before executing the loop body.
Syntax: while (condition)
{
statement(s);
}
Here is the flow of control in a while loop:
while is keyword
condition: The Test condition is evaluated and if the condition is true, then the body of the
loop is executed. After execution of the body, the test condition is once again evaluated and if
it is true, the body is executed once again. This process of repeated execution of the body
continues until the test condition is true. The test condition must be enclosed with in
parentheses.
Body of the loop: The body of the loop may have one or more statements. The braces are
needed only if the body contains two or more statements.
Flow Diagram
Output: value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example: C# Program to Find Magnitude of Integer
using System;
class Program
{
public static void Main()
{
int num, mag=0;
Console.WriteLine("Enter the Number : ");
num = int.Parse(Console.ReadLine());
Console.WriteLine("Number: " + num);
while (num > 0)
{
mag++;
num = num / 10;
}
Console.WriteLine("Magnitude: " + mag);
Console.Read();
}
}
Do...While Loop: Similar to while loop, but it tests the condition at the end of the loop body. The
block of code inside do while loop will execute at least once even though the condition is false.
Syntax: do
{
statement(s);
}while( condition );
Where do and while are two keywords.
Here the body of the loop is executed first. At the end of the loop, the condition in the while
statement is evaluated. If the condition is true, the program continues to execute the body of
the loop once again. This process continues as long as the condition is true. When the
condition becomes false, the loop will be terminated and the control goes to the statements
that appears immediately after the while statement. Remember the body of the loop is always
executed at least once.
There is semicolon at the end of while(condition); in do-while loop
Flow Diagram
{
class Program
{
static void Main(string[] args)
{
int a = 10;
do
{
Console.WriteLine("value of a: {0}", a);
a = a + 1;
} while (a < 20);
Console.ReadLine();
}
}
}
Output: value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Nested Loops: C# allows to use one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax: for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C# is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C# is as follows:
do
{
statement(s);
do
57 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For
example a for loop can be inside a while loop or vice versa.
Example: Write a program uses a nested for loop to find the prime numbers from 2 to 50
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
int i, j;
for (i = 2; i < 20; i++)
{
for (j = 2; j <= (i / j); j++)
if ((i % j) == 0) break;
if (j > (i / j))
Console.WriteLine("{0} is prime", i);
}
Console.ReadLine();
}
}
}
Output: 2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
LOOP CONTROL STATEMENTS: A Loop control statement alters the normal execution path of
a program. Loop control statements are used when we want to skip some statements inside loop or
terminate the loop immediately when some condition becomes true.
Break Statement: When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop. It can be used to
terminate a case in the switch statement. If you are using break statement in nested loops (i.e., one
loop inside another loop), the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.
Syntax: break;
Flow Diagram:
58 School of Computer Science & Engineering | RGMCET
C# AND .NET
Continue Statement: The continue statement is used to skip some part(s) of loop's body. It means
We can use continue statement inside any loop (for, while and do-while). It skips the remaining
statements of loop's body and starts next iteration.
Syntax: continue;
Flow Diagram:
position. The position of the last item of an array will totalnumber of items-1.so if an array has 10
items, the last 10th item is at 9th position.In C#, arrays can be declared as fixed length or dynamic.
Fixed length arrays: A fixed length array can store a predefined number of items.
Dynamic arrays: A dynamic array does not have a predefined size. The size of a dynamic
array increases as you add new items to the array.
To access an element we can use array name and index value of the concern (or) particular
element.
In c# arrays are reference types. Hence it stores default values based on data type.
Types of Arrays: C# .NET supports three types of arrays.
One-dimensional array: Arranging collection of elements in a single row can be called One-
dimensional array.
Or
A list of items can be given under single variable name using only one subscript is called single
subscripted variable (or) One-dimensional array.
All items in a single dimension array are stored contiguously starting from 0 to the size of the array-
1.
Declaration: Like other variables arrays must be declared before they are used. To declare an array
in C#, you can use the following syntax:
Syntax: datatype[] arrayName=new data type[size];
or
data type[] arrayname;
arrayname=new datatype[size];
or
int[] arrayname={list of values};
Where,
data type- It is used to specify the type of elements in the array.
[ ]- specifies subsciptinal operator.
Size-specifies the size of the array.
array name-specifies the name of the array.
new-memory allocation operator.
Example: int[] a=new int[10];
Or
double[] balance;
balance=new double[5];
Initializing an Array: Once an array is declared, the next step is to initialize an array. The
62 School of Computer Science & Engineering | RGMCET
C# AND .NET
initialization process of an array includes adding actual data to the array. Array is a reference type, so
you need to use the new keyword to create an instance of the array.
Example: You can assign values to the array at the time of declaration as shown:
double[] balance = { 2340.0, 4523.69, 3421.0};
Example: You can also create and initialize an array as shown:
int [] marks = new int[5]{ 99,98, 92, 97, 95};
Example: You may also omit the size of the array as shown:
int [] marks = new int[] { 99,98, 92, 97, 95};
You can copy an array variable into another target array variable. In such case, both the target and
source point to the same memory location (Both the array will have same values).
int [] marks = new int[] { 99,98, 92, 97, 95};
int[] score = marks;
When you create an array, C# compiler implicitly initializes each array element to a default value
depending on the array type. For example, for an int array all elements are initialized to 0.
Example: using System;
namespace ArrayApplication
{
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;
for (j = 0; j < 10; j++ )
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
Console.ReadKey();
}
}
}
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
Example: using System;
namespace One_Dimensional_Array
63 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
class Program
{
static void Main(string[] args)
{
string[] Books = new string[5];
Books[0] = "C#";
Books[1] = "Java";
Books[2] = "VB.NET";
Books[3] = "C++";
Books[4] = "C";
Console.WriteLine(“Element of Books array is:\n\n");
int i = 0;
Console.Write("\t1\t2\t3\t4\t5\n\n\t");
for (i = 0; i < 5; i++)
Console.Write("{0}\t", Books[i]);
Console.ReadLine();
}
}
}
foreach Loop: It is specially designed for accessing the value of an array (or) collection( list, hash-
table, stack, queue and linked list) where for each iteration of the loop one value of the array is
assigned to the loop variable and the return to us.
Syntax: foreach(type variable_name in expression)
{
Body of the loop;
}
Where,
type-specifies the data type
variable_name-specifies the array variable name.
in- it is a keyword.
expression - specifies array type or collection type.
Example: using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10];
for ( int i = 0; i < 10; i++ )
n[i] = i + 100;
foreach (int j in n )
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console.ReadKey();
}
}
}
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
Example: using System;
namespace store_value_in_array
{
class Program
{
static void Main(string[] args)
{
int i;
int[] arr = new int[5]; // 5 size array
for (i = 0; i < 5; i++)
{
Console.Write("\nEnter your number:\t");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\n\n");
for (i = 0; i < 5; i++)
{
Console.WriteLine("you entered {0}", arr[i]);
}
Console.ReadLine();
}
}
}
Example: using System;
namespace accessing_array_value
{
class Program
{
static void Main(string[] args)
{
int[] age=new int[6];
string[] name = new string[6];
int i,j=0;
string find;
for (i = 0; i < 6; i++)
{
65 School of Computer Science & Engineering | RGMCET
C# AND .NET
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.
Declaration: Like other variables arrays must be declared before they are used. To declare an array
in C#, you can use the following syntax:
Syntax: datatype[,] arrayName=new data type[rows , columns];
or
data type[,] arrayname;
arrayname=new datatype[rows , columns];
or
int[,] arrayname={list of values};
Where,
data type- It is used to specify the type of elements in the array.
[ ]- specifies subsciptinal operator.
rows-specifies the row size .
column-specifies the column size .
array name-specifies the name of the array.
new-memory allocation operator.
Example: int[,] a=new int[10,5];
Or
double[,] balance;
balance=new double[5,5];
Initializing Two-Dimensional Arrays: Multidimensional arrays may be initialized by specifying
bracketed values for each row. The following array is with 3 rows and each row has 4 columns.
int [,] a = int [3,4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The following code creates two multi-dimensional arrays with no limit.
int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
You can also omit the new operator as we did in single dimension arrays. You can assign these
values directly without using the new operator. For example:
int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
string[,] names = { { "Rosy", "Amy" }, { "Peter", "Albert" } };
We can also initialize the array items one item at a time. The following code is an example of
initializing array items one at a time.
int[,] numbers = new int[3, 2];
numbers[0, 0] = 1;
numbers[1, 0] = 2;
numbers[2, 0] = 3;
numbers[0, 1] = 4;
numbers[1, 1] = 5;
numbers[2, 1] = 6;
Example: using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 2; j++)
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
Console.ReadKey();
}
}
}
Output: a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Array (or) arrays of arrays (or) dynamic arrays: Jagged array is collection rows which
contain distinct number of elements in each row that means all the rows may not contain same
number of elements.
Or
Jagged array is collection of one-dimensional arrays of varying size.
Declaration: Declaration of a jagged array involves two brackets.
type[][] array_name = new type[3][];
or
type[][] array_name={list of values};
Initialization: Before a jagged array can be used, its items must be initialized. The following code
snippet initializes a jagged array; the first item with an array of integers that has two integers, second
item with an array of integers that has 4 integers, and a third item with an array of integers that has 6
integers.
Example:
int[][] ar=={new int[]{1,2,3},new int[]{1,2,3,4},new int[]{1,2}};
type[][] array_name = new type[3][];
intJaggedArray[0] = new int[2]{2, 12};
intJaggedArray[1] = new int[4]{4, 14, 24, 34};
intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };
Example: example illustrates using a jagged array:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{{new int[]{0,0},new int[]{1,2},
new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
int i, j;
/* output each array element's value */
for (i = 0; i < 5; i++)
{
for (j = 0; j <; 2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}",i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
}
Output: a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
Passing Arrays as Function Arguments: You can pass an array as a function argument in C#.For
this we follow the rules.
1. The function must be called by passing only the name of the array and the size of the array.
Syntax: max(a,n);
2. In the function definition, the formal parameter must be an array type; the size of the array does
not need to specified.
3. The function header might look like:
Syntax: float max(float[] array , int size)
using System;
namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;double avg;int sum = 0;
for (i = 0; i < size; ++i)
sum += arr[i];
avg = (double)sum / size;
return avg;
}
static void Main(string[] args)
{
MyArray app = new MyArray();
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = app.getAverage(balance, 5 ) ;
/* output the returned value */
Console.WriteLine( "Average value is: {0} ", avg );
Console.ReadKey();
}
}
}
Output: Average value is: 214.4
Variable argument list (or) Param Arrays: At times, while declaring a method, you are not sure of
the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into
help at such times.in C# we can define methods that can handle variable number of arguments is
called parameter arrays. Parameter arrays are declared using the keyword params.
Only one params keyword is allowed and no additional parameter is allowed after params keyword
in a function declaration.
Example: using System;
namespace ArrayApplication
{
class p
{
Public void show(params,int[] val)
{
for(int i=0;i<val.length;i++)
{
Console.WriteLine(val[i]);
}
public static void Main(string[] args)
{
p p1=new p();
P1.show();
}
}
}
class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}
Output: The sum is: 2938
Array Class: The Array class is the base class for all the arrays in C#. Array Class is defined in the
System namespace. In C# every array is automatically derived from the System.Array class. The
Array class provides various properties and methods to work with arrays.
Properties of the Array Class: The following table describes some of the most commonly used
properties of the Array class:
S.No Property name Description
1 Length Gets a 32-bit integer that represents the total number of
elements in all the dimensions of the array.
2 Rank Gets the rank (number of dimensions) of the array.
3 IsFixedSize Gets a value indicating whether the array has fixed size.
4 IsReadOnly Gets a value indicating whether the array is read only
5 LongLength Gets a 64-bit integer that represents the total number of
elements in all the dimensions of the array.
Methods of the Array Class: The following table describes some of the most commonly used
methods of the Array
S.No Property name Description
1 Clear Sets the range of elements in the array to zero, to false,
(or) to null, depending on the element type.
2 Copy() Copies the range of elements from an array starting at the
first element and pastes them into another array
3 CopyTo() Copies all the elements of the current one dimensional
array to the specified one dimensional array starting at the
specified destination array index.
4 GetLenth Gets a 32-bit integer that represents the number of
elements in the specified dimension of the array.
Example: Write a program of sorting an array. Declare single dimensional array and accept 5
integer values from the user. Then sort the input in ascending order and display output.
using System;
namespace Example1
{
class Program
74 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
static void printarray(int[] arr)
{
Console.WriteLine("\n\nElements of array are:\n");
foreach (int i in arr)
{
Console.Write("\t{0}", i);
}
}
static void Main(string[] args)
{
int[] arr = new int[5];
int i;
for (i = 0; i < 5; i++)
{
Console.Write("Enter number:\t");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Program.printarray(arr);
Array.Sort(arr); //use array's sort function
Program.printarray(arr);
Console.ReadLine();
}
}
}
Differences between for and foreach loop:
S.No for foreach
1 Loop variable refers to the index of an Loop variable refers to the values of an array
array.
2 Loop variable is integer type The type of the loop variable is similar to the
type of values inside an array
3 It is used for both accessing and assigning It is used only for accessing.
values to an array
STRINGS: String represents sequence of characters. C# supports two types of strings.
Mutable strings(dynamic strings)
Immutable strings
Immutable strings: String objects are immutable, meaning that we cannot modify the characters
contained in them. String is alias for the predefined System.String class in the CLR, there are many
built in operations available that work with strings.
C# also supports regular expressions that can be used for complex string manipulations and pattern
matching.
Creating a String Object: C# supports a predefined reference type known as string. We can use
string to declare string type objects. You can create string object using one of the following methods:
By assigning a string literal to a String variable
string s2=s1.Insert(3,”r”);
string s3=s2.Insert(5,”er”);
for(int i=0;i<s3.Length;i++)
{
Console.Write(s3[i]);
}
}
}
In the above program ,when the statement
string s2=s1.Insert(3,”r”);
is executed, the string variable s2 contains the string “Learn”. The string “r” is inserted in s1 after 3
characters. Similarly, the string “er” is inserted at the end of the string. Finally the variable s3
contains the value “Learner”.
Example: Take two inputs as string from the users and copies the input of string2 to string5 and
checks for the string3 ends with IDE or not. The program shows true if string3 ends with IDE.
Searches char ‘a’ from the string1.Insert hello in string6 at position 6 and shows the atring6.
using System;
namespace SearchString
{
class Program
{
public void Display()
{
string str1=””;
Console.Write(“Enter a string”);
str1=Console.ReadLine();
string str2=””;
Console.Write(“Enter another string”);
str2=Console.ReadLine();
string str3=”C# 2005 is developed in Visual Studio 2005IDE”;
Console.Write(“string str3 is {0}”,str3);
string str5=string.Copy(str2);
Console.Write(“ string str5 is copied from str2: {0}”,str5);
Console.Write(“ string str5 is {0} characters long:”,str5.Length);
Console.Write(“ the 10th character of string str3 is : {0}”,str3[9]);
Console.Write(“ string str3 {0} \n ends with IDE?:
{1}\n”,str3,str3.EndsWith(“IDE”));
Console.Write(“Ends with studio?:{0}”,str3.EndsWith(“studio”));
Console.Write(“\n the first time character ‘a’ occurred in string str1 at
position:{0}”,str1.IndexOf(“a”+1);
String str6=str2.Insert(6,”hello”);
Console.Write(“ ’hello’ is inserted in string str6.string str6 is noe:
{0}”,str6);
}
static void Main()
{
Program prg=new Program();
Prg.Display();
}
}
}
Comparing Strings: String class supports overloaded methods and operators to compare whether
two strings are equal or not. They are
Overloaded Compare() Method
Overloaded Equals() Method
Overloaded == operator
Compare() method: There are two versions of overloaded static Compare() method. The first one
takes two strings as parameters and compares them.
Example: int n=string.Compare(s1,s2);
This performs case-sensitive comparison and returns different integer values for different conditions
as under:
Zero , if s1 is equal to s2.
A positive integer(1), if s1>s2.
A negative integer(-1), if s1<s2.
s1=”hello”; s2=”hello”; s3=”csharp”; s4=”mello”
s1,s2=0
s2,s3=1
s3,s4=-1
Example: s1=”abc”
s2=”ABC”;
int n=string.Compare(s1,s2);
Output: n value is -1.
The second version of Compare () method takes an additional bool type parameter to decide whether
case should be ignored or not. If the bool parameter is true, case is ignored.
Example: int n = string.Compare(s1,s2,true);
Example: s1=”abc”
s2=”ABC”;
int n=string.Compare(s1,s2,true);
output: n value is 0.
Example: using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
79 School of Computer Science & Engineering | RGMCET
C# AND .NET
Mutable strings: string objects are mutable, meaning strings are modifiable. Mutable strings are
created using StringBuilder class.
Example: StringBuilder str1=new StringBuilder(“abc”);//with initial size of three
characters
StringBuilder str2=new StringBuilder(); //empty string
The string object str1 is created with an initial size of three characters and str2 is created as an empty
string. They can grow dynamically as more characters are added to them.
The StringBuilder class supports many methods that are useful for manipulating dynamic strings.
StringBuilder mehods:
S.No Method Operation
1 Append() Appends a string
2 AppendFormat() Appends string using specific format
3 EnsureCapacity() Ensure sufficient size
4 Insert() Insert a string at a specified position
5 Remove() Removes the specified characters
6 Replace() Replaces all instances of a character with a specified one.
C# also supports some special functions known as properties.
StringBuilder properties:
S.No Method Operation
1 Capacity To retrieve or set the number of characters the object can hold
2 Length To retrieve or set the length
3 MaxCapacity To retrieve the maximum capacity of the object
4 [] To get or set a character at a specified position.
The System.Text namespace contained the StringBuilder class and therefore we must include the
using System.Text directive for creating and manipulating mutable strings.
Example: using System.Text; using System;
class StringBuilderMethod
{
public static void Main()
{
StringBuilder s=new StringBuilder(“object”);
Console.WriteLine(“original string:”+s);
Console.WriteLine(“length:”+s.Length);
s.Append(“language”);
Console.WriteLine(“String now:”+s);
s.Insert(7,”oriented”);
Console.WriteLine(“modified string:+s);
int n=s.Length;
s[n-1]=’!’;
Console.WriteLine(“”final string:”+s);
}
}
Output: original string: object
Length : 7
String now: object language
Modified string: object oriented language
Final string: object oriented language!
Example: program to accept two string inputs from users and appends the first string to a predefined
value. Using StringBuilder class, a string value is inserted in the string. Then, all spaces in first are
replaced with * and the program calculates the length of two strings after appending.
Arrays of strings: The statement
string[] itemarray=new string[3];
the above will create itemarray of size 3 to hold three strings. we can assign the strings to the
itemarray element by element using 3 different statements (or) using for loop.
string[] itemarray={”a”,”b”,”c”};
Example: using System;
class Strings
{
public static void Main()
{
string[] countries={“india”,”Germany”,””America”,”France”};
int n=countries.Length;
Array.Sort(countries);
for(int i=0;i<n;i++)
Console.WriteLine(countries[i]);
Array.Reverse(countries);
for(int i=0;i<n;i++)
Console.WriteLine(countries[i]);
}
}
Regular expressions: Regular expressions provide a powerful tool for searching and manipulating a
large text. A regular expression may be applied to a text to accomplish tasks such as.
To locate substrings and return them.
To modify one (or) more substrings and return them.
To identify substrings that begins with (or) ends with a pattern of characters.
To find all words that begins with a group of characters and end with some other characters.
To find all occurrences of a substring.
A regular expression is a string containing two types of characters.
Literals: These are characters that we wish to search and match in the text.
Metacharacters: These are special characters that give commands to the regular expression parser.
Examples:
S.No Expression Meaning
1 “\bm” Any word beginning with m
2 “er\b” Any word ending with er
3 “\BX\B” Any X in the middle of the word
4 “\bm\S*er\b” Any word beginning with m and ending with er.
5 “|,” Any word separated by a space or a comma
In the above table ,\b,\B,\S* and | are metacharacters and m, er, X and comma are literals.
The .NET framework provides support for regular expression matching and replacement. The
namespace System.Text.RegularExpressions support a number of classes that can be used for
searching, matching and modifying a text document. The important classes are
Regex
MatchCollection
Match
Example: using System;
82 School of Computer Science & Engineering | RGMCET
C# AND .NET
using System.Text;
using System.Text.RegularExpressions;
class RegexTest
{
public static void Main()
{
string str;
str=”amar,akbar,antony are friends”;
Regex reg=new Regex(“|,”);
stringBuilder sb=new StringBuilder();
int count=1;
foreach(string sub in reg.Split(str))
sb.AppendFormat(“{0}:{1}\n”,count++,sub);
Console.WriteLine(sb);
}
}
Output: 1:amar
2:akbar
3:antony
4:are
5:friends
STRUCTURES: Structure is collection of data items of different type.
Or
A structure is a collection of heterogeneous data elements
Structures are similar to classes in C#.
In C# structure is a value type data type.
Defining a Structure: To define a structure, you must use the struct keyword.
Syntax: struct struct_name
{
Data member1;
Data member2;
Data member3;
}
Or
struct struct_name
{
Data member1;
Data member2;
Data member3;
};
In the above code the keyword struct declares Books as a new data type that can hold three variables
of different data types. These variables are known as members or elements.
Declaring structure variables: we can declare structure variables using the structure-tag in the
program. A structure variable declaration is similar to the declaration of variables of any other data
types. It includes the following elements.
The structure tag name
List of variable names separated by commas
A terminating semicolon
Syntax: structure_tag structure_var1, structure _var2,........structure _varN;
Example: Books book1,book2,book3;
Each one of the variables has three members as specified by the template.
Assigning values to structure members: Structure members can be accessed using the simple dot
notation.
Syntax: structurevariablename.structuremember= value;
Example: book1.title=”c#”;
book1.author=”raja”;
book1.subject=”c sharp”;
Copying Structure Variables Two variables of the same structure type can be copied the same way
as ordinary variables. If person1 and person2 belongs to the same structure, then the fallowing
assignment operations are valid:
person1 = person2; ------ assigns person1 to person2
person2 = person1; ------ assigns person2 to person1
Note:
1. we can also use the operator new to create stricture variables
Syntax: struct-tag structure-variable=new struct-tag();
Example: books b1=new books();
2. Structure members are by default private and therefore cannot be accessed outside the
structure definition.
Example: The following program shows the use of the structure:
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1;
Books Book2;
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject ="Telecom Billing Tutorial";
Book2.book_id = 6495700;
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
Output: Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Example: The following program shows the use of the structure:
using System;
namespace Structure
{
class Program
{
struct book
{
public string bookname;
public int price;
public string category;
}
static void Main(string[] args)
{
book language, database;
Console.Write("Enter book name:\t");
language.bookname = Console.ReadLine();
Console.Write("Enter book price:\t");
language.price=Convert.ToInt32(Console.ReadLine());
Console.Write("Enter book category:\t");
language.category = Console.ReadLine();
Console.Write("\n\nEnter book name:\t");
85 School of Computer Science & Engineering | RGMCET
C# AND .NET
database.bookname = Console.ReadLine();
Console.Write("Enter book price:\t");
database.price=Convert.ToInt32(Console.ReadLine());
Console.Write("Enter book category:\t");
database.category = Console.ReadLine();
Console.Write("\n\n===================");
Console.Write("\n\t\tLanguage\n");
Console.Write("===================\n\n");
Console.Write("BookName:\t{0}",language.bookname);
Console.Write("\nBook Price:\t{0}", language.price);
Console.Write("\nBook Category:\t{0}", language.category);
Console.Write("\n\n==================\n");
Console.Write("\t\tDatabase\n");
Console.Write("====================\n\n");
Console.Write("BookName:\t{0}",database.bookname);
Console.Write("\nBookPrice:\t{0}",database.price);
Console.Write("\nBookCategory:\t{0}",database.category);
Console.ReadLine();
}
}
}
Output: Enter book name : C Sharp
Enter book price : 34
Enter book category : Object Oriented Programming
Enter book name : SQL Server
Enter book price : 23
Enter book category: Database Programming
=============================================
Language
=============================================
Enter book name : C Sharp
Enter book price : 34
Enter book category: Object Oriented Programming
=============================================
Database
=============================================
Enter book name : SQL Server
Enter book price : 23
Enter book category : Database Programming
Structures with methods: we have seen that values may be assigned to the data members using
structure_variable and the dot operator. We can also assign values to the data members using what
are known as constructors.
A constructor is a method which is used to set values of data members at the time of
declaration.
Example: struct Number
{
int number; // data member
{
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
88 School of Computer Science & Engineering | RGMCET
C# AND .NET
/* book 1 specification */
Book1.getValues("C Programming", "Nuha Ali","C Programming
Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing", "Zara Ali", "Telecom Billing
Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
Output: Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
Features of C# Structures: The C# structures have the following features:
Structures can have methods, fields, indexers, properties, operator methods, and events.
Structures can have defined constructors, but not destructors. However, you cannot define a
default constructor for a structure.
Structures cannot inherit other structures or classes. Structures cannot be used as a base for
other structures or classes.
A structure can implement one or more interfaces.
Structure members cannot be specified as abstract, virtual, or protected.
When you create a struct object using the new operator, it gets created and the appropriate
constructor is called. structs can be instantiated without using the New operator.
If the New operator is not used, the fields remain unassigned and the object cannot be used
until all the fields are initialized.
Enumerationas: Enumerated Types allow us to create our own symbolic names for a list of related
ideas. It is defined as
Syntax: enum Identifier{Value 1,value 2,…..value n};
Example: enum shape
{
Circle;
Square;
Triangle;
}
Or
89 School of Computer Science & Engineering | RGMCET
C# AND .NET
enum shape
{
Circle;
Square;
Triangle;
};
enum: It is the keyword which allows the user to create our own symbolic names for a list of ideas.
Identifier: It is the name of enumerated data type
Example: enum day{mon,tue,wed….sun};
The compiler automatically assign integer digits beginning with 0 to all enumeration constants, that
is value1=0,value2=1……however the programmer can change the default values.
enum day{ mon=0,tue=10,wed=20...sun=15};
Example: The following example demonstrates use of enum variable:
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
static void Main(string[] args)
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: {0}", WeekdayStart);
Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}
Output: Monday: 1
Friday: 5
Enumerator initialization: As mentioned earlier, by default, the value of the first enum number is
set to 0, and that of each subsequent member is incremented by one. However we may assign
specific values for different members.
Example: enum Days
{
Sun=1;
Mon=3;
Sat=5;
}
We can also have expressions.
Example: enum Days
{
Sun=1;
90 School of Computer Science & Engineering | RGMCET
C# AND .NET
Mon=Mon+3;
Sat=Sun+Mon+5;
}
If the declaration of an enum member has no initializer, then its value is set implicitly as follows.
Example: enum Alphabet
{
A,
B=5,
C,
D=20,
E
}
Output: A=0
B=5
C=6
D=20
E=21
Enumerator base types: By default, The type of an enum is int .However, we can declare explicitly
a base type for each enum.The valid base types are: byte, sbyte, short, ushort, int, uint, long and
ulong.
Example: enum Position:byte
{
Off;
On:
}
The values assigned to the members must be within the range of values that can be represented by
the base type.
Enumerator type conversion: enum types can be converted to their base types and back again with an
explicit conversion using a cast .
Example: enum values
{
Value0;
Value1;
Value2;
}
--------
--------
Values u1=(Values) 1;
int a=(int) u1;
Example: using system
class Enumtype
{
enum Direction
{
North,
East==10,
West,
South
}
public static void Main()
{
Direction d1=0,
Direction d2= Direction.East;
Direction d3= Direction.West;
Direction d4= (Direction)12;
Console.WriteLine(“d1=”+d1);
Console.WriteLine(“d2=”+(int)d2);
Console.WriteLine(“d3=”+d3);
Console.WriteLine(“d4=”+d4);
}
}
Output: d1=North
d2=10
d3=West
d4=South
Example: write a c# program which stores values in two enumerations, Staff and Company. It
uses two functions to display the data contained in Staff and Company enumerations.
using system;
enum Staff { Directors, Managers, Executives }
enum Company
{
Newsoftltd,
Technologieslnc,
Hillrockltd
}
class program
{
public static void Show(staff st)
{
switch(st)
{
case staff.Directors: Console.WriteLine(“you are a director”);
break;
case staff.Managers: Console.WriteLine(“you are a manager”);
break;
case staff.Executives: Console.WriteLine(“you are a executive”);
break;
default: break;
}
}
public static void CompDisplay(Company com)
{
switch(st)
{
case Company. Newsoftltd: Console.WriteLine(“Newsoftltd”);
break;
92 School of Computer Science & Engineering | RGMCET
C# AND .NET
UNIT II
93 School of Computer Science & Engineering | RGMCET
C# AND .NET
C# is true object oriented programming language. All object oriented languages employ three core
principles, namely
Encapsulation
Abstraction
Inheritance
Polymorphism
These are often referred as pillars (or) building blocks of oop.
Encapsulation (or) data hiding (or) information hiding: Encapsulation is the process of
hiding irrelevant data from the user . The outside users may not be able to change the state of an
object directly. However, the state of an object may be altered indirectly using the access modifier
keywords public, private and protected. To understand encapsulation, consider an example of
mobile phone. Whenever you buy a mobile, you don’t see how circuit board works. You
are also not interested to know how digital signal converts into analog signal and vice
versa. These are the irrelevant information for the mobile user, that’s why it is
encapsulated inside a cabinet.
Inheritance: It is the concept we use to build new classes using the existing class definitions. The
original class is known as base (or) parent class and the modified one is known as derived class (or)
subclass (or) child class. Inheritance provides the reusability of existing code and thus improves
integrity of programs and productivity of programmers.
Polymorphism: It is the ability to take more than one form. For example, an operation may exhibit
different behaviour in different situations. The behaviour depends upon the types of data used in the
operation. for example, an addition operation involves two numeric values will produce a sum and
same addition operation will produce a string if the operands are string values instead of numbers.
Abstraction: Abstraction is just opposite of Encapsulation. Abstraction is mechanisim to show only
relevent data to the user . Consider the same mobile example again. Whenever you buy a mobile
phone,you see their different types of functionality as camera, mp3, player, calling function,
recording function, multimedia, etc. It is abstraction, because you are seeing only relevant
information instead of their internal enginnering.
CLASSES: It is a collection of objects.
Or
A class is a blueprint of an object that contains variables for storing data and functions to
perform operations on the data.
Or
length=x;
width=y;
}
}
Note that the method has a return type void because it does not return any value. We pass two integer
values to the method, which are then assigned to the instance variables length and width. The
GetData() method is basically added to provide values to the instance variables. Now we are able to
use directly length and width inside the method.
Example: class Rectangle
{
int length;
int width;
public void GetData(int x,int y)
{
length=x;
width=y;
}
public int RectArea()
{
int area=length*width;
return area;
}
}
The method RectArea() computes the area of the rectangle and returns the result.
Member access modifiers: C# provides a set of access modifiers that can be used with the members
of a class to control their visibility to outside users.
Modifier Accessibility control
private Private members of a class are completely restricted and are
accessible only within the class in which they are declared.
public Member is accessible from anywhere outside the class as well. It is accessible in
derived classes.
protected Member is visible only its own class and its derived classes
internal Member is available with in the assembly that is being created and not
accessible in outside namespace
Protected Available in the containing program or assembly and in the derived classes.
internal (outside the namespace)
In C# all members have private access by default. If we want a member to have any other visibility
range, then we must specify a suitable access modifier to it individually.
Example: class Visibility
{
public int x;
internal int y;
protected double d;
float p;
}
Local variables: The variables which are declared within the method is called local variables.
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Volume of Box1 : {0}",volume);
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
Output: Volume of Box1 : 210
Volume of Box2 : 1560
Main(): as mentioned earlier, C# programs start execution at a Main() method. This method must be
static method of a class and must have either int or void return type.
public static int Main()
public static void Main()
The Main() method can also have parameters which may receive values from the command line at
the time execution.
public static int Main(string[] args)
public static void Main(string[] args)
METHOD: A method is a self-contained block of code that performs a particular task. Every C#
program has at least one class with a method named Main.
Defining Methods (or) declaring methods: methods are declared inside the body of the class,
normally after the declaration of data fields.
Syntax:
< Access modifier > <Return Type> <Method Name> (Parameter List)
{
Method Body
}
Where,
Method name: Method name is a valid c# identifier and it is case sensitive. It cannot be same as any
other identifier declared in the class.
Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data
from a method. The parameter list refers to the type, order, and number of the parameters of a
method. Parameters are optional; that is, a method may contain no parameters.
Method body: This contains the set of instructions needed to complete the required activity and
method body can be enclosed in curly braces.
Return type: Return type specifies the type of value the method will return. If the method is not
returning any values, then the return type is void.
Access modifier: This determines the visibility of a variable or a method from another class.
Console.ReadLine();
}
}
}
Output: Max value is : 200
Example:
using System;
namespace CalculatorApplication
{
class Method
{
int Cube(int x)
{
return (x*x*x);
}
}
class MethodTest
{
static void Main(string[] args)
{
Method M = new Method();
int y=M.Cube(5);
Console.WriteLine("y” );
}
}
}
Output: Max value is: 125
Nesting of methods: we have earlier that a method can be called only by an object of that class if it
is called outside the class. We can also called a method without using any object or dot operator. That
is, a method can be called only its name by another method of the same class. This is known as
nesting of methods.
Example: using System;
class nesting
{
void largest(int m,int n)
{
int large=Max(m,n);
Console.WritLine(large);
}
int Max(int a, int b)
{
int x=(a>b)?a:b;
return x;
}
}
class nesttesting
{
public static void Main()
101 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
nesting next=new nesting();
next.largest(100,200);
}
}
Method parameters:
Input parameters: Input parameters are used for bringing a value into the method for
execution.
Value parameters: Value parameters are used for passing parameters into methods by value.
Reference parameters: Reference parameters are used to pass parameters into methods by
reference.
Output parameters: Output parameters are used to pass results back from a method.
Parameter arrays: Parameter arrays are used in a method definition to enable it to receive
variable number of arguments when called.
Parameters Passing Methods: There are three ways that parameters can be passed to a method.
Passing Parameters by Value: In this type value of actual arguments are passed to the formal
arguments of the called function. Any changes made in the formal arguments does not effect the
actual arguments in the calling function.
Or
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter cannot be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of
actual parameter is copied to formal parameter.
Example:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
int a = 100;
int b = 200;
class Rectangle
{
public void swap(int x,int y,out int h, out int k)
{
int temp;
temp = x;
x = y;
y = temp;
h = x;
k = y;
}
static void Main(string[] args)
{
Rectangle n = new Rectangle();
int a = 100;
int b = 200; int d, c;
Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);
n.swap(a,b,out d,out c);
Console.WriteLine("After swap, value of a : {0}", d);
Console.WriteLine("After swap, value of b : {0}", c);
Console.ReadLine();
}
}
}
Variable argument list (or) Param Arrays: At times, while declaring a method, you are not sure of
the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into
help at such times.in C# we can define methods that can handle variable number of arguments is
called parameter arrays. Parameter arrays are declared using the keyword params.
Example:
using System;
namespace ArrayApplication
{
class ParamArray
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
sum += i;
return sum;
}
}
class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
106 School of Computer Science & Engineering | RGMCET
C# AND .NET
using System.Text;
namespace ConsoleApplication3
{
class Method_overloading
{
public int Addition(int a, int b)
{
int x;
return x=a+b;
}
public int Addition(int a, int b,int c)
{
int y;
return y = a + b+ c;
}
public float Addition(float a, float b)
{
float u;
return u = a + b;
}
public float Addition(float a, float b, float c)
{
float v;
return v = a + b+ c;
}
}
class hub
{
public static void Main(String[] args)
{
Method_overloading mthover = new Method_overloading();
Console.WriteLine("Addition of two integers::::::::::::::::" + mthover.Addition(2, 5));
Console.WriteLine("Addition of two double type values::::::" + mthover.Addition(0.40f, 0.50f));
Console.WriteLine("Addition of three integers::::::::::::::" + mthover.Addition(2, 5, 5));
Console.WriteLine("Addition of three double type values:" + mthover.Addition(0.40f, 0.50f, 0.60f));
Console.ReadLine();
}
}
}
Example:
using System;
namespace LineApplication
{
class Line
{
private double length;
public Line()
{
Console.WriteLine("Object is being created");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
Result: Object is being created
Length of line : 6
Parameterized Constructors: A constructor with at least one parameter is called as parameterized
constructor. The advantage of a parameterized constructor is that you can initialize each instance of
the class to different values.
Example: using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh");
Sample obj1=new Sample("Welcome1","Aspdotnet-Suresh1");
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.WriteLine(obj1.param1 +" to "+ obj1.param2);
Console.ReadLine();
}
}
}
Output: Welcome to Aspdotnet-Suresh
Welcome1 to Aspdotnet-Suresh1
Copy Constructor: The constructor which creates an object by copying variables from another
object is called a copy constructor. Main purpose of copy constructor is to initialize new object to the
values of an existing object. Here the copy constructor contains a parameter, which is of class type.
Example: using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet-Suresh");
Sample obj1=new Sample(obj);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
Output: Welcome to Aspdotnet-Suresh
Static Constructor: A static constructor is used to initialize any static data (or) to perform a
particular action that needs to be performed once only. static constructor will be invoked only once
for all the objects of the class. Static constructor gets called when the first object of the class is
created.
111 School of Computer Science & Engineering | RGMCET
C# AND .NET
Once we provide a constructor that is either private or public or any, the compiler will not
allow us to add public constructor without parameters to the class.
If we want to create object of class even if we have private constructors then we need to have
public constructor along with private constructor
Example: using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample() // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}
Output: Welcome to Aspdotnet-Suresh
Note: In above method we can create object of class with parameters will work fine. If create object
of class without parameters it will not allow us create.
// it will works fine
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();
Example: using System;
namespace defaultConstractor
{
public class Counter
{
private Counter() //private constrctor declaration
{
}
public static int currentview;
public static int visitedCount()
113 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
return ++ currentview;
}
}
class viewCountedetails
{
static void Main()
{
// Counter aCounter = new Counter(); // Error
Console.Write("Private constructor example ");
Console.WriteLine();
Counter.currentview = 500;
Counter.visitedCount();
Console.WriteLine(" view count is: {0}",
Counter.currentview();
Console.ReadLine();
}
}
}
Constructor Overloading: The process of creating more than one constructor with same name,
which is similar to class name, but with different parameters is called constructor overloading.
Example: using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y)
// Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj= new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh");
// Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
114 School of Computer Science & Engineering | RGMCET
C# AND .NET
}
}
Output: Hi, I am Default Constructor
Welcome to Aspdotnet-Suresh
C# DESTRUCTORS: A destructor is a special method that is automatically executed when an
object is destroyed. A destructor has exactly the same name as that of the class name with a prefixed
tilde (~) and without return a value and without access specifier. Destructor can be very useful for
releasing memory resources before exiting the program. Destructors cannot be inherited or
overloaded.
Example: using System;
namespace LineApplication
{
class Line
{
private double length;
public Line()
{
Console.WriteLine("Object is being created");
}
~Line()
{
Console.WriteLine("Object is being deleted");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
}
Output: Object is being created
Length of line : 6
Object is being deleted
STATIC CONCEPTS:
Static Classes: C# provides the feature to create static classes. There are two main features of static
classes
We cannot create object for static classes
115 School of Computer Science & Engineering | RGMCET
C# AND .NET
Static Members: The members of a class that can be accessed without creating an
instance and directly by using class name are called as static members.
Static variable: a variable that is declared by using a static modifier (or) a variable
that is declared inside of any static block is called static variable.
Example: class MySettings
{
public static int height;
public static int width = 20;
}
a static variable is get initialized immediately once the execution of class starts.
A static variable is initialized one time in the life cycle of the class.
A static variable of the class can be accessed using the class name.
Static Methods: A method that is declared by using a static modifier is called static
method. When a method is declared as static then that method can access only other
static members available in the class and it is not possible to access instance members
static int max(int x, int y);
Example: using system;
namespace example
{
class mathoperation
{
public static float mul(float x, float y)
{
return x*y;
}
public static float divide(float x, float y)
{
return x/y;
}
}
class mathapplication
{
public static void Main()
{
float a=mathoperation.mul(4.0f,5.0f);
float b=mathoperation.divide(a,2.0f);
Console.WriteLine(“b=”+b);
}
}
}
Example: using system;
namespace example
{
class MySettings
{
private static int height = 100;
private static int width = 150;
public static void MyMethod()
{
Console.WriteLine("{0},{1}", height, width);
}
}
class AllSettings
{
public static void Main()
{
MyClass.MyMethod();
}
}
Example: using system;
namespace Static_var_and_fun
{
class number
{
// Create static variable
public static int num;
//Create static method
public static void power()
{
Console.WriteLine("Power of {0} = {1}", num, num * num);
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number\t");
number.num = Convert.ToInt32(Console.ReadLine());
number.power();
}
}
}
CONSTANTS: constants are immutable values which are known at compile time and do not change
for the life of the program. Constants are declared using const modifier.
The const modifier is used to declare constant variables that cannot be changed.
Constant variables must be given initial values when they are declared.
public cons int size=100;
The behaviour of const variable is similar to static variable, except const variable cannot be
modified.
Example: using System;
namespace UsingConst
{
class Program
{
const int a = 10;
static void Main(string[] args)
{
const int b = 20;
const int c = b + a;
Console.WriteLine(c);
Console.ReadLine();
}
}
}
readonly variable: A readonly field can be initialized either at the time of declaration or with in the
constructor of same class. Therefore, readonly fields can be used for run-time constants.
Only values are assigned to readonly fields,then those must be same throughout the application.
Example: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}
public SampleClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
static void Main()
{
SampleClass k1 = new SampleClass(11, 21, 32);
Console.WriteLine("k1:x={0},y={1},z={2}",p1.x,p1.y,p1.z);
SampleClass k2 = new SampleClass();
k2.x = 55;
Console.WriteLine("k2:x={0},y={1},z={2}",p2.x,p2.y,p2.z);
}
}
}
this reference: The this keyword refers to the current instance of the class. This reference is
available within all the member methods and always refers to the current instance. It is used to
distinguish local and instance variables that have the same name.
Example: using System;
class Demo
{
int a=2,b=10;
public void Get()
{
int a=23,b=34;
Console.WriteLine("a={0} b={1}",this.a,this.b);
Console.WriteLine("It is the class variable");
Console.WriteLine("Now the local variables are:");
Console.WriteLine("a={0} b={1}",a,b);
}
}
class MainClass
{
static void Main(string args[])
{
Demo d= new Demo();
d.Get();
}
}
Nesting of classes: To define a class within the scope of another class is called nesting of classes.
Syntax: public class outer
{
……..
……..
public class inner
{
…….
…….
}
}
Example: using System;
namespace innerclassexample
{
public class nestedclass
{
public static void Main()
{
outerclass obj2=new outerclass();
obj2.show();
outerclass.innerclass obj1=new outerclass.innerclass();
obj1.display();
}
}
Public class outerclass
{
public void show()
{
Console.WriteLine(“outer class”);
}
public class innerclass
{
public void display()
{
Console.WriteLine(“innerclass class”);
}
}
}
INHERITANCE: One of the most important concepts in object-oriented programming is
inheritance.
Creating a new class from existing class is called as inheritance
(Or)
Acquiring (taking) the properties of one class into another class is called inheritance.
(Or)
When a new class needs same members as an existing class, then instead of creating
those members again in new class, the new class can be created from existing class,
which is called as inheritance.
Main advantage of inheritance is reusability of the code. During inheritance, the class
that is inherited is called as base class and the class that does the inheritance is called
as derived class.
Base class: is the class from which features are to be inherited into another class.
Syntax: class base-class-name
{
Members of class
}
Derived class: it is the class in which the base class features are inherited.
Syntax: class derived-class-name: base-class-name
{
Members of class
}
Types of inheritance: Inheritance can be classified into 5 types
1. Single Inheritance
2. Hierarchical Inheritance
3. Multi-Level Inheritance
121 School of Computer Science & Engineering | RGMCET
C# AND .NET
4. Hybrid Inheritance
5. Multiple Inheritance
Single Inheritance: when a single derived class is created from a single base class then
the inheritance is called as single inheritance.
Syntax: class A
{
----
----
}
class B:A
{
----
----
}
Example: using System;
namespace InheritanceApplication
{
class a
{
public void display()
{
System.Console.WriteLine("hahahaha");
}
}
class b : a //b is child of a
{
public void display1()
{
System.Console.WriteLine("hihihih");
}
}
class c
{
public static void Main()
{
b x=new b();//Normally object of child
x.display();
x.display1();
}
}
}
Example: using System;
namespace InheritanceApplication
122 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
Console.WriteLine("Total area: {0}",Rect.getArea());
Console.ReadKey();
}
}
}
Output: Total area: 35
Hierarchical Inheritance: when more than one derived class are created from a single
base class, then that inheritance is called as hierarchical inheritance.
Syntax: class A
{
----
----
}
class B:A
{
----
----
}
class C:A
{
----
----
}
Example: C# Program to Illustrate Hierarchical Inheritance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inheritance
{
class Program
{
static void Main(string[] args)
{
Principal g = new Principal();
g.Monitor();
Teacher d = new Teacher();
d.Monitor();
d.Teach();
Student s = new Student();
s.Monitor();
s.Learn();
Console.ReadKey();
}
class Principal
{
public void Monitor()
{
Console.WriteLine("Monitor");
}
}
class Teacher : Principal
{
public void Teach()
{
Console.WriteLine("Teach");
}
}
class Student : Principal
{
public void Learn()
{
Console.WriteLine("Learn");
}
}
}
}
124 School of Computer Science & Engineering | RGMCET
C# AND .NET
Multi-Level Inheritance: when a derived class is created from another derived class,
then that inheritance is called as multi-level inheritance.
Syntax: class A
{
----
----
}
class B:A
{
----
----
}
class C:B
{
----
----
}
Example: C# Program to Illustrate Multilevel Inheritance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class a
{
public void display()
{
Console.WriteLine("hahahaha");
}
}
class b : a //b is child of a
{
public void display1()
{
Console.WriteLine("hihihih");
}
}
class d : b //d is child of b
{
public void display2()
{
Console.WriteLine("hohohohoh");
}
125 School of Computer Science & Engineering | RGMCET
C# AND .NET
}
class c
{
public static void Main()
{
d x = new d();//Normally object of child
x.display();
x.display1();
x.display2();
}
}
}
Hybrid Inheritance: Any combination of single, hierarchical and multi-level
inheritances is called as hybrid inheritance.
Multiple Inheritance: when a derived class is created from more than one base class
then that inheritance is called as multiple inheritance.
But multiple and hybrid inheritance is not supported by .net using classes and can be
done using interfaces.
POLYMORPHISM: Polymorphism means one name many forms (ability to take more than one
form). In Polymorphism poly means “multiple” and morph means “forms” so polymorphism means
many.In polymorphism we will declare methods with same name and different parameters in same
class or methods with same name and same parameters in different classes. Polymorphism has ability
to provide different implementation of methods that are implemented with same name.
Types of polymorphism:
Compile Time Polymorphism(or)Early Binding (or) Overloading (or) static binding
Run Time Polymorphism(or)Late Binding (or) Overriding (or) dynamic binding
Static Polymorphism: The mechanism of linking a function with an object during compile time is
called early binding. It is also called static binding. C# provides two techniques to implement static
polymorphism. They are:
1. Function (or) method overloading
2. Constructor overloading.
126 School of Computer Science & Engineering | RGMCET
C# AND .NET
3. Operator overloading
Function (or) method Overloading: The process of creating more than one method in a
class with same name is called as method overloading. The definition of the function must
differ from each other by the types and/or the number of arguments in the argument list.
Example: using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
p.print(5);
p.print(500.263);
p.print("Hello C++");
Console.ReadKey();
}
}
}
Output: Printing int: 5
Printing float: 500.263
Printing string: Hello C++
Example: using System;
namespace MethodOverloadingByManishAgrahari
{
class Program
{
public class TestOverloading
{
public void Add(string a1, string a2)
{
Console.WriteLine("Adding Two String :" + a1 + a2);
}
public void Add(int a1, int a2)
{
Console.WriteLine("Adding Two Integer :" + a1 + a2);
}
}
static void Main(string[] args)
{
TestOverloading obj = new TestOverloading();
obj.Add("Manish " , "Agrahari");
obj.Add(5, 10);
Console.ReadLine();
}
}
}
Constructor Overloading: The process of creating more than one constructor with same name,
which is similar to class name, but with different parameters is called constructor overloading.
Example: using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y)
// Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj= new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh");
// Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
Output: Hi, I am Default Constructor
Welcome to Aspdotnet-Suresh
OPERATOR OVERLOADING: This is something very much similar to the concept of method
Unary operator overloading: In case of unary operators, the argument must be the same type as
that of enclosing class or struct
Example: using System;
class bank
{
int x;
int y;
public bank(int a, int b)
{
x = a;
y = b;
}
public bank()
{
}
public void display()
{
Console.Write(" " + x);
Console.Write(" " + y);
Console.WriteLine();
}
public static bank operator -(bank b)
{
b.x = -b.x;
b.y = -b.y;
return b;
}
}
class program
{
public static void Main()
{
bank ba1 = new bank(10,-20);
ba1.display();
bank ba2 = new bank();
ba2.display();
ba2 = -ba1;
ba2.display();
Console.ReadLine();
}
}
Output: 10 -20
1 0
-10 20
130 School of Computer Science & Engineering | RGMCET
C# AND .NET
}
public complexNumber()
{
}
public static complexNumber operator +(complexNumber c1,
complexNumber c2)
{
complexNumber c = new complexNumber();
c.x=c1.x+c2.x;
c.y=c1.x-c2.y;
return c;
}
public void show()
{
Console.Write(x);
Console.Write("+j"+y);
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
complexNumber p, q, r;
p = new complexNumber(10, 2.0);
q = new complexNumber(20, 15.5);
r = p + q;
Console.Write("p=");
p.show();
Console.Write("q=");
q.show();
Console.Write("r=");
r.show();
Console.ReadLine();
}
}
}
Output: p=10+j2
Q=20+j15.5
R=30+j-5.5
Example: using System;
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public double getVolume()
{
132 School of Computer Science & Engineering | RGMCET
C# AND .NET
Console.ReadLine();
}
}
}
Output: v1 and v2 are not equal
Dynamic Polymorphism (or) Run time polymorphism (or) late binding (or) method overriding:
The process of re-implementing the parent class method under the child class with same name and
same signature is called method overriding. Method overriding means same method names with
same signatures in different classes. In this run time polymorphism or method overriding we can
override a method in base class by creating similar function in derived class this can be achieved by
using inheritance principle and using “virtual & override” keywords. In base class if we declare
methods with virtual keyword then only we can override those methods in derived class
using override keyword.
Syntax: class A
{
public virtual void show()
{
---
---
}
}
class B:A
{
public override void show()
{
----
----
}
}
Notes:
1. Overriding virtual method of parent class under child class is only optional for child classes.
2. When a method overrides under the child class. The object of the child class gives the
preference to local method and invokes the method it has overridden, but not the virtual
method of parent.
3. Using the base keyword we can invoke the virtual method of the parent class from child class
after overriding. Using the base keyword in the static blocks is not possible.
Example: using System;
namespace OperatorOvlApplication
{
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new BClass();
objBc.Sample1();
}
}
}
Output: Derived Class
Base Class
Example: using System;
namespace methodoverriding
{
class Program
{
static void Main(string[] args)
{
employee obj = new employee();
obj.display();
Console.ReadLine();
}
}
public class cls
{
public virtual void display()
{
Console.WriteLine("hello");
}
}
public class employee : cls
{
public override void display()
136 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
Console.WriteLine("welcome");
}
}
}
Overloading Overriding
It is implementing multiple method with same It is implementing multiple method with same
name and different signature name and same signature
This can be performed in one single class as This can be performed only in child class
parent/child classes also.
To overload a parent class method under child To override a parent class method under child
class we do not need any permission from class we require an explicit permission from
parent parent
This is all about providing multiple behaviour This is all about changing the behaviour of the
to a method. method.
METHOD HIDING (OR) SHADOWING: This is another approach for re-implementing a parent
class method under child class even if they are not declared as virtual that re-implementation is
performed without parent class permission.This can be done using new keyword .The compiler hides
the function (or) method of base class.
Syntax: class A
{
public void show()
{
---
---
}
}
class B:A
{
public new void show()
{
----
----
}
}
Example: using System;
namespace App
{
class base
{
public void display()
{
Console.WriteLine(“base method”);
}
}
class derived:base
{
public new void display()
{
Console.WriteLine(“derived method”);
}
}
class test
{
public static void Main()
{
derived d=new derived();
d.display();
}
}
Output: derived method
Note: we can hide an inherited member using new, new does not remove the member, its only makes
the member inaccessible in the derived class.
ABSTRACT CLASS: In c sharp Abstract class is defined using "abstract" keyword. When a class
contains at least one abstract method, then the class must be declared as abstract class.
If an Abstract class contain any abstract methods, then those methods must be implemented under
the child class using override modifier.
Characteristics of abstract classes:
1. Abstract Class cannot be instantiated directly.
2. Abstract Class can have both abstract methods and non-abstract methods.
3. If any child class of abstract class wants to consume non abstract method of its parent, first
they require to implement all the abstract methods of parent otherwise consuming non
abstract methods of parent will not be possible.
4. An abstract class can consume only by child classes that to after providing the
implementation for all the abstract methods of abstract class.
5. You cannot declare an abstract method outside an abstract class
6. When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared
sealed.
Syntax: abstract class class1
{
public abstract void add(int x, int y);
}
ABSTRACT METHOD: A method without method body is known as abstract method. It contains
only declaration of the method. We can define abstract method using abstract keyword.
Characteristics of abstract methods:
1. Abstract method cannot have implementation.
2. Abstract method implementation must be provided in non-abstract derived classes by
overriding the method using override modifier.
139 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
private int length;
private int width;
public Rectangle( int a, int b)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
Output: Rectangle class area: Area: 70
SEALED CLASSES (PREVENTING INHERITANCE): A class that cannot be subclassed is called
sealed class. Sealed classes can be created using sealed modifier.
Some points to remember:
a class, which restricts inheritance for security reason is declared, sealed class.
Sealed class is the last class in the hierarchy.
Sealed class can be a derived class but can't be a base class.
A sealed class cannot also be an abstract class. Because abstract class has to provide
functionality and here we are restricting it to inherit.
Syntax: accessmodifier sealed class classname
{
------
------
}
Example: class1
{
public virtual void show()
{
----
----
}
}
class2
{
141 School of Computer Science & Engineering | RGMCET
C# AND .NET
}
//public class Derived : BaseClass
// {
// this Derived class can;t inherit BaseClass because it is sealed
//}
static void Main(string[] args)
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}
}
}
SEALED METHOD: when an instance method declaration includes the sealed modifier, the
method is called sealed method. It means a derived class cannot be override this method. Sealed
keyword is always used with override keyword.
Syntax: access_modifier sealed override returntype methodname(Params_list)
{
----
----
}
Example: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_method
{
class Program
{
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Virtual method");
}
}
public class DerivedClass : BaseClass
{
// Now the display method have been sealed and can;t be overridden
public override sealed void Display()
{
Console.WriteLine("Sealed method");
}
}
//public class ThirdClass: DerivedClass
//{
//public override void Display()
//{
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
public interface PaintCost
{
int getCost(int area);
}
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
Console.WriteLine("Total area: {0}",
Rect.getArea());
Console.Write("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
Output: Total area: 35
Total paint cost: $2450
{
Console.WriteLine("output values{0},{1}", x, y);
}
}
class test
{
public static void Main()
{
partialclass p=new partialclass(10,15);
p.print();
Console.ReadLine();
}
}
}
Output: output values 10, 15
Note: we use partial classes in windows application development.
WHY DELEGATES: Delegates are used in the following cases:
Delegates can be used to handle (call/invoke) multiple methods on a single event.
Delegates can be used to define call-back (asynchronous) methods.
Delegates can be used for decoupling and implementing generic behaviours.
Delegates can be invoked method at runtime.
Delegates can be used in LINQ for parsing the Expression Tree.
Delegates can be used in different Design Pattern.
DELEGATES:
Definition: A delegate object is a special type of object that contains the details of a method
rather than data.
Or
Delegate is a class type object and is used to invoke a method that has been encapsulated into it
at the time of its creation.
Or
A delegate (known as function pointer in C/C++) is a references type that invokes
single/multiple method(s) through the delegate instance.
Or
Delegate is an object, which can be used to invoke the functionality of other object without
knowing its class name or method name.
inside a class
outside all classes
as the top level object in a namespace
Delegates are implicitly sealed and therefore it is not possible to derive any type from a delegate
type.
Delegate methods: the methods whose references are encapsulated into a delegate instance are
known as delegate methods (or) callable entities. The return type and signature of delegate methods
must exactly match the signature and return type of the delegate. Delegate methods do not care about
What type of object the method is being called against.
Whether the method is a static or an instance method.
Example: delegate string getastring ();
The above delegate can made to refer to the method ToString() using an int object N as follows
int N=100;
getastring s1=new getastring(N.ToString);
Example: delegate void delegate1 ();
The above delegate can encapsulate references to the following methods
public void F1()
{
Console.WriteLIne(“F1”);
}
static public void F2()
{
Console.WriteLIne(“F2”);
}
Example: delegate double mathop (double x, double y);
The above delegate can refer any one of the following methods.
public static double multiply(double a, double b)
{
return (a*b);
}
public double divide(double a, double b)
{
return (a/b);
}
Note: In example2 and example3, the signature and return type of methods match the signature and
type of the delegate.
Delegate instantiation: the syntax for delegate instantiation is
Syntax: new delegate-type (expression)
Where,
Delegate-type: It is the name of the delegate declared earlier whose object is to be created.
Expression: It must be a method name or a value of a delegate type. If it is a method name its
signature and return type must be the same as those of the delegate. If no matching method exists, or
more than one matching method exists, an error occurs. The matching method may be either an
instance method or a static method. If it is an instance method, we need to specify the instance as
well as the name of the method. It is a static one, then it is enough to specify the class name and
method name.
Example: delegate int productdelegate(int x,int y);
class delegate
{
static float product(float a, float b) //signature does not match
{
return (a*b);
}
static int product(int a,int b) //signature matches
{
return (a*b);
}
productdelegate p=new productdelegate(product);
}
Here, we have two methods with same name but with different signatures. The delegate p is
initialized with the reference to the second product method because that method exactly matches the
signature and return type of productdelegate. If this method is not present, an error will occur.
Note: The method and instantiation statement are within the same class, we simply use the method
name for creating the instance.
Example: delegate void displaydelegate();
class A
{
public void displayA()
{
Console.WriteLine(“DisplayA”);
}
}
class B
{
static public void display()
{
Console.WriteLine(“DisplayB”);
}
}
------
-------
A a=new A();
displaydelegate d=new displaydelegate(a.displayA);
displaydelegate d1=new displaydelegate(B.displayB);
The above code defines two delegate methods in two different classes. Since class A defines an
instance method, an A type object is created and used with the method name to initialize the delegate
object d.The delegate method defined in class B is static and therefore the class name is used directly
with the method name in creating the delegate object d1.
Delegate invocation: C# uses a special syntax for invoking a delegate. When a delegate is invoked,
it in turn invokes the method whose reference has been encapsulated into the delegate (only if their
signatures match).
Syntax: delegate_object (parameter list);
The parameters list provides values for the parameters of the method to be used
1. if the invocation invokes a method that returns void, the result is nothing and therefore it
cannot be used as an operand of any operator. It can be simply a statement_expression.
Example: delegate1(x,y); //void delegate: this delegate invokes a method that does
not return any value
2. If the method returns a value, then it can be used as an operand of any operator. Usually, we
assign the return value to an appropriate variable for further processing
Example: double result=delegate2 (2.56, 45.63); //this statement invokes a method
(that takes two double values as parameters and returns double type value) and then assigns
the returned value to the variable result.
Types of Delegates: There are three types of delegates that can be used in C#.
Single Delegate
Multicast Delegate
Single Delegate: single cast delegate can point to a single method at a time and used to invoke a
single method.
Example: demonstrates declaration, instantiation, and use of a delegate that can be used to reference
methods that take an integer parameter and returns an integer value.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
152 School of Computer Science & Engineering | RGMCET
C# AND .NET
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
Output: Value of Num: 35
Value of Num: 175
Multicast Delegate (or) combinable delegates: Multicast delegate can point multiple methods in
order to invoke multiple methods at the time of invocation.
Or
A collection of single cast delegates are called multi cast delegate.
Multicast delegates must specify the following conditions.
The return type of the delegate must be void
None of the parameters of the delegate type can be declared as output parameters, using out
keyword.
If d is the delegate that satisfies the above conditions and d1, d2, d3 and d4 are the instances of d
then the statements.
d3=d1+d2; //d3 refers two methods
d4=d3-d2; // d4 refers only d1 method
The multicast delegates uses arithmetic operators such as + and -. + is used to add a method into
sequence and – is used to delete a method from sequence.
Example: using System;
delegate void mdelegate();
namespace DelegateAppl
{
class dm
{
static public void display()
{
Console.WriteLine(“new delhi”);
}
static public void print()
{
Console.WriteLine(“new york”);
153 School of Computer Science & Engineering | RGMCET
C# AND .NET
}
}
class mtest
{
public static void Main()
{
mdelegate m1=new mdelegate(dm.display);
mdelegate m2=new mdelegate(dm.print);
mdelegate m3=m1+m2;
mdelegate m4=m2+m1;
mdelegate m5=m3-m2;
m3();
m4();
m5();
}
}
}
Output: new delhi
new york
new york
new delhi
new delhi
Example: using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
154 School of Computer Science & Engineering | RGMCET
C# AND .NET
exception object and throws it(that is informs us that an error has occurred).
If the exception object not caught and handled properly, the compiler will display an error message
and will terminate the program. If we want the program to continue with the execution of remaining
code, then we should try to catch exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as exception handling.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
Syntax for exception handling: The basic concepts of exception handling are throwing an exception
and catching it.
try: whenever an exception is expected from a block of statements, then write those statements in try
block..
catch: A catch block defined by the keyword catch. A catch block catches the exception thrown by
the try block and handles it appropriately. The catch block is added immediately after the try block.
Syntax: try
{
Statements; // generates an exception
}
catch (Exception e)
{
Statements; // process the exception
}
The try block can have one or more statements that could generate an exception. If anyone statement
generates an exception, the remaining statements in the block are skipped and execution jumps to the
catch block that is placed next to the try block. The catch block also can have one or more
statements that are necessary to process the exception (remember every try statement should be
followed by at least one catch statement; otherwise compilation error will occur. The catch statement
is passed a single parameter, which is the reference to the exception object thrown by the try block. If
the catch parameter matches with the type of exception object, then the exception is caught and
statements in the catch block will be executed. Otherwise, the exception is not caught and the default
exception handler will cause the execution to terminate.
Example: using System;
class error3
{
public static void Main()
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(Exception e)
{
Console.WriteLine(“division by zero”);
}
y=a/(b+c);
}
}
Output: division by zero
y=1
Note that program did not stop at the point of exceptional condition. It catches the error condition,
prints the error message and then continues the execution as if nothing has happened.
Multiple catch statements: it is possible to have more than one catch statement in the catch block.
try
{
Statements; // generates an exception
}
catch(Exception-type1 e)
{
Statements; // process the exception1
}
catch(Exception-type2 e)
{
Statements; // process the exception2
}
.
.
.
catch(Exception-typeN e)
{
Statements; // process the exception N
}
When an exception in the try block is generated, the c# treats the multiple catch statements like cases
in a switch statement. The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will be skipped.
Note: C# does not require any processing of the exception at all. We can simply have a catch
statement with an empty block to avoid the program abortion.
Example: catch(Exception e){}
The above statement will catch an exception and then ignore it.
Example: using System;
class error3
{
-----
}
The above code will generate a compile time error, because the exception is caught by the first catch
(which is more general one) and the second catch is therefore unreadable.In C#, having unreachable
code is always an error
Example: try
{
// throws divide by zero exception
}
catch(DivideByZeroException e)
{
-----
-----
}
catch(Exception e)
{
-----
-----
}
The order of catch blocks is important. We must start with catch blocks that are designed to trap very
specific exceptions and finish with more general blocks that will cover any other exceptions for
which we have not provided handlers.
General catch handler: A catch block will catch any exception is called a general catch handler. A
general catch handler does not specify any parameter.
Syntax: try
{
----//causes an exception
}
catch
{
---- // handles an error
----
}
Note that catch (Exception e) can handle all the exceptions thrown by the C# code and therefore can
be used as a general catch handler. However, if the program uses libraries written in other languages,
then there may be an exception that is not derived from the class Exception. Such exceptions can be
handled by parameter-less catch statement. This handler always placed at the end. Since there is no
parameter, it does not catch any information about the exception and therefore we do not know what
went wrong.
Using finally statement: C# supports another statement known as a finally statement that can be
used to handle an exception that is not caught by any of the previous catch statements. A finally
block can be used to handle any exception generated within a try block. It may be added immediately
160 School of Computer Science & Engineering | RGMCET
C# AND .NET
Or
try
{
----
----
}
catch(……)
{
----
----
}
catch(……)
{
----
----
}
.
.
.
finally
{
----
----
}
When finally block is defined, the program is guaranteed to execute, regardless of how control leaves
the try, whether it is due to normal termination, due to an exception occurring or due to a jump
statement.
Example: using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
161 School of Computer Science & Engineering | RGMCET
C# AND .NET
}
public void division(int num1, int num2)
{
try
{
{
----
----
}
finally
{
----
----
}
When nested try blocks are executed, the exceptions that are thrown at various points are handled as
follows:
The points p1 and p4 are outside the inner try block and therefore any exceptions thrown at
these points will be handled by the catch in the outer block.The inner block is simply ignored.
Any exception thrown at point p2 will be handled by the inner catch handler and the inner
finally will be executed. The execution will continue at point p4 in the program.
If there is no suitable catch handler to catch an exception thrown at p2, the control will leave
the inner block (after executing the inner finally) and look for a suitable catch handler in the
outer block. If a suitable one if found, then that handler is executed followed by the outer
finally code. Remember, the code at point p4 will be skipped.
If an exception is thrown at point p3, it is treated as if it had been thrown by the outer try
block and, therefore, the control will immediately leave the inner block (of course, after
executing the inner finally) and search for a suitable catch handler in the outer block.
In case, a suitable catch handler is not found, then the system will terminate program
execution with an appropriate message.
Example: using System;
class nestedtry
{
static int m=10;
static int n=0;
static void division()
{
try
{
int k=m/n;
}
catch(ArgumentException e)
{
Console.WriteLine(“caught an exception”);
}
finally
{
Console.WriteLine(“inside division method”);
}
}
public static void Main()
{
try
{
division();
}
163 School of Computer Science & Engineering | RGMCET
C# AND .NET
catch(DivideByZeroException e)
{
Console.WriteLine(“caught an exception”);
}
finally
{
Console.WriteLine(“inside main method”);
}
}
}
Creating User-Defined Exceptions or throwing our own exceptions: You can also throw our own
exceptions. We can do this by using the keyword throw. User-defined exception classes are derived
from the System.ApplicationException class.
Syntax: throw new Throwable_subclass;
Examples: throw new ArithmeticException;
throw new FormatException;
Example: using System;
namespace ConsoleApplication8
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature t = new Temperature();
try
{
t.showTemp();
}
catch (TempIsZeroException e)
{
Console.Write("TempIsZeroException:{0}", e.Message);
}
Console.ReadKey();
}
}
public class TempIsZeroException : ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if (temperature == 0)
164 School of Computer Science & Engineering | RGMCET
C# AND .NET
{
throw(newTempIsZeroException("ZeroTemperature
found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
}
Output: TempIsZeroException: ZeroTemperature found
Exception Classes in C#: C# exceptions are represented by classes. The exception classes in C# are
mainly directly or indirectly derived from the System.Exception class. Some of the exception
classes derived from The System.Exception class are the System.ApplicationException and
System.SystemException classes. The System.ApplicationException class supports exceptions
generated by application programs. Hence the exceptions defined by the programmers should derive
from this class. The System.SystemException class is the base class for all predefined system
exception. The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class:
Exception Class Description
SystemException A failed run time check; used as a base class for other
exceptions
AccessException Failure to access a type member, such as a method or field
ArgumentException An argument to a method was invalid
ArgumentNullException A null argument was passed to a method that does not accept it
ArgumentOutOfRangeException Argument value is out of range
ArithmeticException Arithmetic over or underflow has occurred
ArrayTypeMismatchException Attempt to store the wrong type of object in an array
BadImageFormatException Image is in the wrong format
CoreException Base class for exceptions thrown by the runtime
System.IO.IOException Handles I/O errors.
IndexOutOfRangeException An array index is out of range.
DivideByZeroException Handles errors generated from dividing a dividend with zero
InvalidCastException Handles errors typecasting
InvalidOperationException A method was called at an invalid time
MissingMemberException An invalid version of a DLL was accessed
NotFiniteNumberException A number is not valid
NotSupportedException Indicates that a method is not implemented by a class,
NullReferenceException Handles errors generated from dereferencing a null object.
OutOfMemoryException Handles errors generated from insufficient free memory.
StackOverflowException Handles errors overflow
Why Delegates :
Delegates are used to call/invoke multiple methods on a single event.
Delegates can be used to define call-back(asynchronous) methods (A Callback function is a
function passed into another function as an arguments,s)