You are on page 1of 106

Introduction to dotnet framework:

Before the existance of dot net frame work , there were languages such
as vb , vc++ , asp etc were being executed in their respective platforms.

Rather than executing these applications in their respective platforms ,


Microsoft dot net frame work came in.

Where in multiple languages can be executed.

It supports 32 languages.

What is .net :
 It is a platform neutral framework
 .net is a layer between the operating system and programming
lanaguage
 It supports many programming languages , including vb.net , c# etc
 .net provides a common set of libraries , which can be accessed
from any .net based programming language. There will not be
separate set of classes and libraries for each language.

.net is not an operating system


.net is not a programming language.

.net is a framework.

The .net framework :

It is based on common language runtime. The common languge runtime


provides a common set of services for projects built in microsoft visual
studio.net, regardless of the langauge.
These services provide key building blocks for applications of any
type,across all application tiers.

The dotnet frame work comprises a tool called "common language


runtime " (clr) .
Clr : it is the virtual machine component of the .net frame work. All the .net
programs execute under the supervision of the clr , guaranteeing certain
properties and behaviours in the area of memory management, security
checking and exception handling.

Note:
Runtime layer is refered to as clr.

The primary role of the clr is to locate , load and manage .net types.
The clr also takes care of number of low-level details such as memory
management and performing security checks.
Clr manages
 Garbaze collection
 Threading

Clr is one which reads the source code and converts into appropriate
il ( intermediate language)

Another building block of .net platform is the common type system (cts).
The cts specification fully describes all possible data types and
programming constructs supported by the runtime.
It specifies how these entities can interact with each other and details
how they are represented in the .net metadata format.
It is one which identifies the data types.

Common language specification :


It is a specification defines a sub set of common types and programming
constructs that all the programming language meet.

Common type system :


It is a standard that specifies how type definitions and specific values of
types are represented in computer memory.

The role of base class libraries:


In addition to clr , cts /cls specifications , .net platform provides a base
class library.
That is available to all the .net programming languages.
Base class library encapsulates various primitives such as threads , file
input /output (i/o) and interaction with various external hardware devices.

Base class library defines types that facilitate database access ,xml
manipulation ,programming security and construction of web enabled front
ends.

.net solution:
Core features of .net
 Full interoperability with existing code.
Existing com binaries can mingle with newer .net binaries and
vice versa.
Platform invocation services allows user to invoke c-based
libraries from .net code.
 Complete and total language integration.
.net supports cross language inheritance , cross language
exception handling and cross language debugging.

 A common runtime engine shared by all the .net languages.


One aspect of this engine is a well defined set of types that
each .net-aware language understands.
 Base class library
This offers a consistent object model used by all .net aware
languages.

 Simplified deployment model


Under .net , no need to register a binary unit into the system
registry.
.net allows multiple versions of same *.dll to exist in harmony
on a single machine.

The role of common intermediate language:


Cil is a language . It sits above any particular platform specific instruction
set.
The source code is compiled to cil.

Benefit of cil :
The one benefit is language integration.

Each .net aware compiler produces nearly identical cil instructions.


There fore all languages are able to interact with in a well -defined binary
data.
Cil is platform-agnostic.
Compiling cil to platform specific instructions:
Jit : (just in time compiler)
The entity that compiles cil code into meaningful cpu instructions. It can
also be called as jitter.
Jitter compiles cil instructions into corresponding machine code (platform
specific instructions).

Meta data :
Meta data could describe if a component required a database transaction
or if the component should participate in object pooling.

Role of .net type meta data :


The meta data describes each and every type (class, structure
,enumeration and so forth) defined in the binary. As well as the members of
each type (properties , methods,events and so on).
This is called .net binary.

Usage of meta data in .net runtime environment :


Meta data is used in numerous aspect of the .net runtime environment and
also in various development tools.
Ex: intellisense feature in visual studio.
Metadata is also used by various object browsing utilities, debugging tools
and c# compiler.
It is the back bone of many .net technologies including remoting ,
reflection , late binding , xml web services and object serialization.

.net assembly overview:


Compiled program in a .net , the result is a assembly.
Assembly contains cil (common intermediate language ) code and meta
data.

Assembly can also be called as .net binary .


This binary do not contain platform -specific instructions such as il and
type meta data.

C# source code -------------> c# compiler-------------------------------->


Perl .net
Source code ---------------> perl .net compiler----------------->

Il and

Meta data

(*.dll or *.exe)
Cobol .net
Source code -----------------> cobol .net compiler------------>

Manged c++
Source code ----------------> managed c++ compiler---------->

Note:
Cil like java byte code.
Meta data describes the characterstics of every type living with in the
binary.
Ex : it specifies the base class of the user defined class , which interfaces
are implemented.
.net meta data is always present and is automatically generated by a given
.net aware compiler.

In addition to cil and meta data , assemeblies them selves are also
described using meta data which is called as "manifest"

Single file and multi file assembly :


Single file assembly contains all the necessary cil , meta data and
associated manifest in an autonomous single well defined package.

Multi file assembly:


It is composed of numerous .net binaries, each of which is termed as
module.

When building multi file assembly one of these module termed the primary
module must contain the assembly manifest(cil instructions and meta
data for various types).
The other module contains cil , type meta data ,module level manifest.
Why multi file assemblies are required :
When the assemblies are partitioned to different modules. It provides more
flexible deployement option.
Ex: remote assembly to be downloaded , the runtime will down load only
required modules.
If all the types are placed in single file assembly. Then while down loading
large volume or chunk of data is down loaded. It is a waste of time

The role of assembly manifest:


Assemblies contain collection of data that describes how the elements in
the assembly relate to each other.
The assembly manifest contains this assembly meta data. Assembly
manifest contains all the meta data needed to specify the assemblies
version requirements and security identity. All the meta data needed to
define the scope of the assembly and resolve references to resources and
classes.
The assembly manifest can be stored in either exe or dll with intermediate
language code.
Assembly manifest performs following function :
 Enumerates the file that make up the assembly
 Enumerates other assemblies on which assembly depends.
 Governs how references to the assemblys types and resources map
to the files that contain their declarations and implementations.
Intrinsic cts data types: (key cts data types)
It is a well defined set of core data types.
Thye are
Cts data types c# keyword

 System.byte byte
 System.sbyte sbyte
 System.int16 short
 System.int32 int
 System.int64 long
 System.uint16 ushort
 System.uint32 uint
 System.uint64 ulong
 System.single float
 System.double double
 System.object object
 System.char char
 System.string string
 System.decimal decimal
 System.boolean bool

.net name spaces :


 System
 System.collection
 System.collection.generic
 System.data
 System.data.odbc
 System.io
 System.data.oledb
 System.data.oracleclient
 System.data.sqlclient
 System.drawing
 System.text
 System.net
 System.reflection
 System.security
 System.web
 System.xml

System :
It is the core name space for programming.
It includes base types like string , datetime, boolean

System.io :
Allows the user to read or write to different streams.

System.data :
This represents ado.net architecture.

System.drawing :
Provides access to gdi graphics functionality.

System.threading
It facilitates multi threading.
C sharp can also be called as ( c#)

C# used to develop asp.net applications and for windows applications.

Variable :
It is a memory location which is used to store or hold the value. The value
entered is not fixed. It varies.

All varibles must be declared , before they are used.

Rules for naming c sharp variables:


 Start each variable name with a letter or under score character
 After the first character , use letters ,digits or the under score
character.
 No reserve key words be used.

Anatomy of basic c# class:


Using system; // importing a name space.

Namespace consoleapplication18
{
Class program
{
Static void main(string[] args)
{
Console.writeline("this is testing");

}
}
}
Using system :
It provides the compiler with knowledge of the types in the system name
space.

Name space is a logical grouping of predefined c# programming elements.


Using : it is a key word (reserver word) . They are tokens that have special
meaning in a language.

The main method serves as the entry point for c# program.


A class declaration in "c#" is composed of attributes, modifiers, the class
name,bases and body.
Attributes , modifiers, bases are optional.
The body contains class members that can include constants, variables,
methods ,operators, and nested types.

Modifiers : it allows the user to control access to the class and to restrict
the ability of the class to be instantiated.
These class modifers are public, protected, internal , private, abstract ,
sealed ,new.

Public access: it is unrestricted.


Protected access : it is restricted to the containing class or to classes
derived from it.
Internal access: it is restricted to containing assembly (program).
Private access: it is restricted to containing class only.
Abstract : this modifier indicates that a class is incomplete and must be
extended by a
Derived class in order to be instantiated.
Sealed: sealed classes cannot be extended. It cannot server as a base for
another class.
New modifer: it is applied only to nested class or other class member. It is
to indicate that it hides an inherited member of the same name.

Class: it is a user defined data type (udt) . It is a blue print.


A class is a template that defines the form of an object.
A class specifies both the data and code that will operate on data.

Object:
It is an instance of a class in memory. New keyword is to create an object.
The new keyword is to aquire sufficient memory from the managed heap
for the specified object.

Class-level scope:
Variables that are defined at class -level become available to any non static
method with in the class.
Private :
These members are available only to that class.

Protected :
These members are available to its own class and to the derived class.

Public:

Internal : the members can be reached from with in the same project only.

Protected internal:
Same as internal . Except that also classes classes which inherits from this
class can reach its members even from another project.

Nested scope:
Variables declared with in the nested scope are not available to those
Outside of their code block.
Ex:
If(condition)
{
String x="abc";
}
X is not available outside if.

Console class:
This class provides a c# application with access to standard input, standard
output, standard error.

Stanard input is associated with the keyboard.


Information can be read from the standard input stream.

Standard output stream is directed to the screen.

Structure:
Structs derive from value system.valuetype. Where as classes derive from
system.object
Structs cannot derive from any other class / struct.
Nor they can be derived from.
C# does not allow structs to have a default parameterless constructor.
(because it is value type).
Struct can implement any number of interfaces.

Even though the "new" keyword is used , struct gets allocated on the
stack.

Interface abc
{
Void get();
}
Struct xyz : abc
{
Public void get()
{
Console.writeline("interface method defined");
}
- }
Class program
{
Static void main(string[] args)
{
Xyz obj = new xyz();
Obj.get();
}
}

Constructor :
It is a special method. It is used when instantiating a class.
It is called automatically as soon as the object or instance is created. It is
used to initialize the data memers of the class.

Note: constructor has the same name as that of the class name.
Constructor does not have return type.

Class sample
{
Public sample() // constructor
{
}
}

Types of constructor:
 Default constructor
 Parameterized constructor

Default constructor : it is one which does not contain any argument.

Every c# class is automatically provided with a default constructor.


It ensures that all data member is set to an default value.

Constructor overloading:
A class having several constructors , but with different parameters.

The composition of c# application:


C# and .net platform are closely coupled. Every application will begin with a
connection to the .net framework . The developer access the portion of
the .net platform.
Using system;
Using system.collections.generic;
Using system.text;

Namespace consoleapplication25
{
Class program
{
Static void main(string[] args)
{
Console.writeline("this is simple program");
}
}
}
The first three lines are name spaces.
Console is a class. Writeline() is a method.
Console class is available in system name space.
The class is declared with the keyword "class" and then name of the
class.
And in the braces , definition and methods of the class are written.

Method defintion is c# is like


[modifiers] return_type methodname( paramters)
{
// method body
}
Ex:
Public void display(int x)
{
}

Variables and constants:


Variables declared in c# as
Datatype variablename;
Ex: int x;

The varible declared with in the loop . Then its scope will be limited to that
loop.

If the variable is declared with in the code block like method then its scope
will be limited to that class.

If the class variable then its scope will be limited to that class.

Constant is also a variable whose values cannot be changed during the


execution of the program.

Default assignment: it is a rule states that every variable must have a


value before it is read from.
The process of assigning a value to a variable for the first time is known as
initialization.

Initialization ensures that , variable have valid values when expressions are
evaluated.
Value types and reference types :
Value types directly contain their data and instances of value types are
either allocated on the stack or allocated inline in a structure.

Reference types:
Reference types store a reference to the values memory address and
are allocated on the heap.

Default values of class member variables:


Using system;
Using system.collections.generic;
Using system.text;

Namespace consoleapplication1
{
Class temp
{
Public int x;
Public string s;
Public bool b;
Public object obj;
}

Class program
{
Static void main(string[] args)
{
Temp t = new temp();
Console.writeline(t.x); // 0
Console.writeline(t.s); //null
Console.writeline(t.b);//false
Console.writeline(t.obj);//null

}
}
}
Member variable initialization :
Using system;
Using system.collections.generic;
Using system.text;

Namespace consoleapplication1
{
Class temp
{
Public int x;
Public string y;
Public temp()
{
X = 100;
}
Public temp(string s)
{
X = 200;
Y = s;
}
Public void put()
{
Console.writeline(x);
}
Public void set()
{
Console.writeline(y);
}
}

Class program
{
Static void main(string[] args)
{
Temp t = new temp();
Temp t1 = new temp("abc");
T.put();
T1.set();
}
}
}

Constant data:
The variable with a fixed and unalterable value.
The keyword const is used.
Any attempt to to alter it results in a compilation error.
Constant variable is known at a compile time.
Constant member cannot be assigned to an object reference.
(because whole value is computed at runtime)
Class consdata
{
Public const string x = "csharp";
Public const double y = 3.14;
Public const bool z = true;
}
Class program
{
Static void main(string[] args)
{
Console.writeline(consdata.x);//referencing const data using
external type
Console.writeline(consdata.y);// prefixing is required
Console.writeline(consdata.z);
Consdata.x = "xyz"; //wrong
Consdata.y = 24.67; //wrong
Console.writeline(consdata.x);
Console.writeline(consdata.y);
Const int x = 100; //correct ,
current member,no prefixing
Console.writeline(x); //correct

}
}

Note:
Constant fields are implicitly "static"
Object cannot access constant members ,private and protected members .
Class cannot access private members
Private const string x="abc"; // wrong

Static methods:
Using system;
Using system.collections.generic;
Using system.text;

Namespace consoleapplication3
{
Class sample
{
Public static void display()
{
Console.writeline("static method invoked");
}
}
Class program
{
Static void main(string[] args)
{
Sample.display();

}
}
}

Using non static data :


Class savingsaccount
{
Public double curbalance;
Public savingsaccount(double balance)
{
Curbalance = balance;
Console.writeline(curbalance);
}
}

Class program
{
Static void main(string[] args)
{
Savingsaccount s1 = new savingsaccount(1000);
Savingsaccount s2 = new savingsaccount(2000);

}
}

Using static data :


Class savingsaccount
{
Public double curbalance;
Public static double curintrate;

Public savingsaccount(double balance)


{
Curbalance = balance;
Console.writeline(curbalance);
}
Public static void setintrate(double intrate)
{
Curintrate = intrate;
}
Public static double getintrate()
{
Return curintrate;
}
Public void setintrateobj(double intrate)
{
Curintrate = intrate;
}
Public double getintrateobj()
{
Return curintrate;
}

Class program
{
Static void main(string[] args)
{

Savingsaccount s1 = new savingsaccount(1000);


Savingsaccount s2 = new savingsaccount(2000);
S1.getintrateobj();
S2.setintrateobj(.08);
Savingsaccount s3 = new savingsaccount(3000.21);
Savingsaccount.getintrate();
}
}

Static class:

Static class sample


{
Public static void display()
{
Console.writeline("static method invoked");
}
}
Class program
{
Static void main(string[] args)
{
Sample.display();

}
}

Note : for static class object cannot be created.


Static class cannot contain "instance members"
Static class cannot have instance constructor

Below program is wrong

Static class sample


{
Int x;
Public sample()
{
X = 100;
}
Public void put()
{
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
Sample s = new sample();
}
}
Note:
Static class should be having members in static
Ex: constructor or data member or function . All these should be
declared in static.

Below program of static class works :

Static class sample


{
Static int x;
Static sample()
{
X = 100;
}
Public static void put()
{
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
//sample s = new sample();
Sample.put();
}
}

Class savingsaccount
{
Public double curbalance;
Public static double curintrate;

Public savingsaccount(double balance)


{
Curbalance = balance;
Console.writeline(curbalance);
}
Public static void setintrate(double intrate)
{
Curintrate = intrate;
}
Public static double getintrate()
{
Return curintrate;
}
Public void setintrateobj(double intrate)
{
Curintrate = intrate;
}
Public double getintrateobj()
{
Return curintrate;
}

Class program
{
Static void main(string[] args)
{

Savingsaccount s1 = new savingsaccount(1000);


Savingsaccount s2 = new savingsaccount(2000);
Double y=s1.getintrateobj();
Console.writeline(y);
S2.setintrateobj(.08);
Savingsaccount s3 = new savingsaccount(3000.21);
Double x=savingsaccount.getintrate();
Console.writeline(x);
}
}

Static constructor:
Any constructor which is preceded with the keyword "static" is static
constructor.

Static constructor does not contain any access modifier.


Static constructor does not take any parameter.
Static constructor executes exactly one time, regardless of how many no of
objects are created.
Static constructor executes before any instance level constructor.
Class sample
{
Int x;
Static sample() // static constructor
{
Console.writeline("static constructor");

}
Public sample(int m)
{
X = m;
Console.writeline(x);
}
}

Class program
{
Static void main(string[] args)
{
Sample s = new sample(100);
}
}

Class sample
{
Int x;
Static sample() // static constructor
{
Console.writeline("static constructor");

}
Public sample()
{
// x = m;
Console.writeline("khkhh");
}
}

Class program
{
Static void main(string[] args)
{
Sample s = new sample();
}
}
Class savingsaccount
{
Public double curbalance;
Public static double curintrate;
Static savingsaccount() //static constructor
{
Curintrate = .05;
}
Public savingsaccount(double balance)
{
Curbalance = balance;
Console.writeline(curbalance);
}
Public static void setintrate(double intrate)
{
Curintrate = intrate;
}
Public static double getintrate()
{
Return curintrate;
}
// public void setintrateobj(double intrate)
// {
// curintrate = intrate;
// }
Public double getintrateobj()
{
Return curintrate;
}
}
Class program
{
Static void main(string[] args)
{

Savingsaccount s1 = new savingsaccount(1000);


Savingsaccount s2 = new savingsaccount(2000);
Double y=s1.getintrateobj();
Console.writeline(y);
// s2.setintrateobj(.08);
Savingsaccount s3 = new savingsaccount(3000.21);
Double x=savingsaccount.getintrate();
Console.writeline(x);
}
}

Note:
Static data member can be accessed inside the static and non static
functions.
Static functions (static constructor and static functions )
Can access only static data members. It does not access non static
members.
Method parameter modifiers:
 None
 Out
 Params
 Ref

None:
If the parameter is not marked with a parameter modifier, it is assumed to
be passed by value, meaning the called method receives a copy of the
original data.

Out:
Output parameters are assigned by the method being called .if the called
method fails to assign output parameters,you are issued a compile error.

Params:
This parameter modifier allows the user to send in a variable number of
identically typed arguments as a single logical parameter.
Member can have only one single params modifier and it must be final
parameter of the method.
Ref:
The value is initially assigned by the caller and may be optionally
reassigned by the called method.

Class sample
{
Public static void fillvalue(out int a, out string b, out bool c)
{
A = 100;
B = "harsha";
C = true;
Console.writeline(a + " " + b + " " + c);
}
}
Class program
{
Static void main(string[] args)
{
Int x;
String y;
Bool z;
Sample.fillvalue(out x, out y, out z);
Console.writeline(x + " " + y + " " + z);

}
}

Class program
{
Public static void fillvalue(out int a,out string b,out bool c)
{
A=100;
B="xxx";
C=true;
Console .writeline (a+" "+b+" "+c);
}
Static void main(string[] args)
{
Int x;
String y;
Bool z;
Fillvalue (out x,out y,out z);

}
}

Using ref parameter:

Class program
{
Public static void swapstring(ref string s1, ref string s2)
{
String tempstr = s1;
S1 = s2;
S2 = tempstr;
}
Static void main(string[] args)
{
String s = "abc";
String s1 = "harsha";
Console.writeline("{0},{1}", s, s1);
Swapstring(ref s, ref s1);
Console.writeline("{0},{1}", s, s1);

}
}

Class program
{
Public static void swap(ref int x, ref int y)
{
Int temp;
Temp = x;
X = y;
Y = temp;
}

Static void main(string[] args)


{
Int a = 100;
Int b = 200;
Console.writeline(a + " " + b);
Swap(ref a, ref b);
Console.writeline(a + " " + b);
}
}

Class program
{
Static void main(string[] args)
{
String[] books ={ "csharp", "java", "dotnet" };
Foreach (string s in books)
{
Console.writeline(s);
}
}
}

Value types and reference types:


Value types variables contain their data.
Each value types variable has its own copy of data.
It is not possible for operations on one variable to affect another variable.

Value types contain


 Built in type
 User defined

Built in type :
Ex: int , float

User defined type :


 Enum
 Struct

Note:
All value types contain data and they cannot be null.

Note:
All of the base data types are defined in the system name space.
All types are derived from system.object

Value types are derived from system.valuetype

Int x =100;

Enumeration types:
Enumerations are use full when a variable can only have a specific set of
values.

Ex:
Enum color {red ,green,blue}

By default enumerator value starts from zero.


Red--0
Green--1
Blue --2

Structures:
Structure is allocated on the stack.

Value types can be removed from the stack once they are out of the
defining scope.

Note:
All structures are derived from system.valuetype

Structures and enumerations extend system.valuetype


Public struct employee
{
Public string name;
Public int age;
}
Class program
{
Static void main(string[] args)
{
Employee e;
E.name ="harsha";
E.age =22;
Console.writeline (e.name + " "+e.age );

}
}

Struct mypoint
{
Public int x, y;
}
Class program
{
Static void main(string[] args)
{
Mypoint p1 = new mypoint();
P1.x = 100;
P1.y = 200;
Mypoint p2 = p1;
Console.writeline(p1.x + " " + p1.y + " " + p2.x + " " + p2.y);
P2.x = 0;
P2.y = 30;
Console.writeline(p2.x + " " + p2.y+" "+p1.x + " "+p1.y);

}
}

Reference type (class)


These are allocated on the heap.
The objects stay in the memory until the garbage collector destroys them.
Class mypoint
{
Public int x, y;
}
Class program
{
Static void main(string[] args)
{
Mypoint p1 = new mypoint();
P1.x = 100;
P1.y = 200;
Mypoint p2 = p1;
Console.writeline(p1.x + " " + p1.y + " " + p2.x + " " + p2.y);
P2.x = 0;
P2.y = 30;
Console.writeline(p2.x + " " + p2.y+" "+p1.x + " "+p1.y);

}
}

Keywords:
These are reserved identifiers.
Abstract , base, bool ,if , finally
Reference types:
Reference type variables contain references to their data.
The data for reference types variables is stored in object.
It is possible for two reference type variables to reference the same object.
Value types containing reference types:
Class shapeinfo
{
Public string x;
Public shapeinfo(string s)
{
X = s;
}
Struct rectangle
{
Public shapeinfo rectinfo; //reference type in value type
Public int top, left, bottom, right;
Public rectangle(string z)
{
Rectinfo = new shapeinfo(z);
Top = left = 10;
Bottom = right = 100;
}
}

Class program
{
Static void main(string[] args)
{
Rectangle r1 = new rectangle("this is rectangle shape");
Rectangle r2;
R2 = r1;
R2.bottom = 4000;
R2.rectinfo.x = "this is new info";
Console.writeline(r1.rectinfo.x);
Console.writeline(r2.rectinfo.x);
Console.writeline(r1.bottom);
Console.writeline(r2.bottom);

}
}
}

Passing reference type by value :


(passing the class object as value)
Using system;
Using system.collections.generic;
Using system.text;

Namespace consoleapplication14
{
Class person
{
Public string fullname;
Public int age;
Public person(string n, int a)
{
Fullname = n;
Age = a;
}
// public person()
// {
// }
Public void printinfo()
{
Console.writeline(fullname + " " + age);
}
}

Class program
{
Public static void display(person p)
{
P.age = 100;
P = new person("abc", 120);
P.printinfo();

}
Static void main(string[] args)
{
Person p1 = new person("harsha", 22);
P1.printinfo();
Display(p1); // passing by value
P1.printinfo();
}
}
}

Passing reference type by reference:


(passing the class object as a reference)

Class person
{
Public string fullname;
Public int age;
Public person(string n, int a)
{
Fullname = n;
Age = a;
}
// public person()
// {
// }
Public void printinfo()
{
Console.writeline(fullname + " " + age);
}
}

Class program
{
Public static void display (ref person p)
{
P.age=55;
P=new person("zzz",999);
}
Static void main(string[] args)
{
Person p1 =new person("xxx",23);
P1.printinfo ();
Display (ref p1); // passing by reference
P1.printinfo ();

}
}

Distinction between value types and reference types:


Value type
reference type
Allocated on the stack allocated on the
heap.
Value type variables are local copies reference type variables are
pointing to the memory occupied by the

allocated instance
Must derive from system.valuetype can derive from other
type
excect system.valuetype
Variables are passed by value variables are passed
by reference

Boxing and unboxing:


Boxing is the process of explicitly converting a value type into
corresponding reference type by storing the variable in a
system.object .

When the value is boxed ,the clr allocates a new object on the heap and
copies the value types value into the instance.
In turn the reference is obtained to the newly allocated object.

Instead of using wrapper classes to treat temporarily stack data as heap


allocated objects.

Un boxing is the process of converting value held in the object reference


back into
Corresponding value type on the stack.
The unboxing operation verifies that the receiving data type is equivalent to
the boxed type. And it copies the value back into a local stack based
variable.
Class program
{
Static void main(string[] args)
{
Int x = 100;
Object obj = x; // boxing
Int y = (int)obj; //un boxing
Console.writeline(y);

}
}
C# compiler automatically boxes variables at appropriate situations.
Ex: passing a value type into a method requiring an object parameter.
Class program
{
Static void main(string[] args)
{
Int x = 100;
Display(x);

}
Static void display(object ob)
{
Console.writeline(ob);
}
}
Note:
Automatic boxing also occurs with the types of .net class library.
Ex:
System.collections name space defines a class type named
"arraylist" .

Class program
{
Static void main(string[] args)
{
Arraylist a = new arraylist();
A.add(100);
A.add(200);
A.add(300);
Foreach (int x in a)
Console.writeline(x);

}
}
Class program
{
Static void main(string[] args)
{
Arraylist a = new arraylist();
A.add(100);
A.add(200);
A.add(300);
//foreach (int x in a)
// console.writeline(x);
Int y = a.count;
For (int i = 0; i < y; i++)
{
Int z = (int)a[i]; // unboxing
Console.writeline(z);
}

}
Unboxing custom value types:
A boxing operation also occurs while passing custom structures or
enumerations into a method prototyped "system.object"

Struct mypoint
{
Public int x, y;
}

Class program
{
Static void main(string[] args)
{
Mypoint m;
M.x=100;
M.y = 200;
Display(m);
}
Static void display(object obj)
{
If (obj is mypoint)
{
Mypoint my = (mypoint)obj; // unboxing
Console.writeline(my.x + " " + my.y);
}
}
}

Working with enumerations:

Enum emptype
{
Manager = 10,
President = 1,
Contractor = 5
}
Class program
{
Static void display(emptype emp)
{
Switch (emp)
{
Case emptype.manager:
Console.writeline("you are manager");
Break;
Case emptype .president:
Console.writeline("you are president");
Break;
Case emptype.contractor:
Console.writeline("you are contractor");
Break;
Default:
Break;
}
}
Static void main(string[] args)
{
Emptype e;
E = emptype.president ;
Display(e);
}
}

Enum emptype
{
Manager = 10,
President = 1,
Contractor = 5
}

Class program
{
Static void main(string[] args)
{
Array obj = enum.getvalues(typeof(emptype));
Console.writeline("this enum has {0} members", obj.length);
Foreach(emptype e in obj)
{
Console.writeline("string name {0}",e.tostring ());
Console.writeline (enum .format (typeof (emptype),e,"d"));

}
}

Master base class: system.object


Class person
{
}
Class program
{
Static void main(string[] args)
{
Person p = new person();
Program p1 = new program();
Console.writeline(p1.gettype().basetype);
Console.writeline(p.gettype().basetype);
}
}

Overriding system.object.tostring()
Class person
{
Private string firstname;
Private string lastname;
Public person(string fname,string lname)
{
Firstname = fname;
Lastname = lname;
}
Public override string tostring()
{
{
Stringbuilder sb = new stringbuilder();
Sb.appendformat("firstname={0}", this.firstname);
Sb.appendformat("lastname={0}", this.lastname);
Return sb.tostring ();
}
}
Class program
{
Static void main(string[] args)
{
String x;
Person p1 = new person("harsha","kumar");
X= p1.tostring();
Console.writeline(x);

}
}

Class program
{
Static void main(string[] args)
{
String s = "dotnet class ";
Console.writeline(s.length);
Console.writeline(s.toupper());
Console.writeline(s.tolower());
Console.writeline(s.substring(3));
Console.writeline(s.remove(5));
Console.writeline (s.insert (2,"dotnet"));
Console.writeline(s.indexof('a'));
Console.writeline(s.replace("dotnet", "java"));

}
}

Escape characters :
\n ----------> new line
\r ------------> carriage return
\t------------> tab space
\\---------->insert back slash
\' -------->insert a quote

Array types:

Array is an user defined data type, which contains consecutive or


continuous memory
Locations of same data type.
Array is a reference type and derive from a common base class called
system.array.

Single dimensional array :


Class program
{
Static void main(string[] args)
{
Int[] z ={ 100, 200, 300 }; //initialization of array
For (int i = 0; i < 3; i++)
Console.writeline(z[i]);
}
}
Class program
{
Static void main(string[] args)
{
Int[] x = new int[] { 10, 20, 30, 40, 50 }; //initializtion of array
//int n;
//console.writeline("enter the value for n ");
// n = int.parse(console.readline());
Console.writeline("enter the value for array \n");
// for (int i = 0; i < 5; i++)
// x[i] = int.parse(console.readline());
Console.writeline("the values of array is ");
For (int i = 0; i < 5; i++)
Console.write(x[i] + " ");
}
}
Class program
{
Static void main(string[] args)
{
Int [] x =new int[10] ;
Int n;
Console.writeline("enter the value for n ");
N = int.parse(console.readline());
Console.writeline("enter the value for array \n");
For (int i = 0; i < n; i++)
X[i] = int.parse(console.readline());
Console.writeline("the values of array is ");
For (int i = 0; i < n; i++)
Console.write(x[i] + " ");
}
}

Arrays as parameters and return values :


Class program
{
Static void printarray(int [] x)
{
For (int i = 0; i < x.length; i++)
Console.writeline(x[i]);
}
Static string[] getstringarray()
{
String[]s ={ "hello", "harsha"};
Return s;
}
Static void main(string[] args)
{
Int [] a= {20,22,30};
Printarray (a);
String[]s1=getstringarray ();
Foreach (string s in s1)
Console.writeline (s);

}
}

Multidimensional arrays:
Class program
{
Static void main(string[] args)
{
Int [,] x =new int[10,10];
Int m, n;
Console.writeline("enter the order of the matrix");
M = int.parse(console.readline());
N = int.parse(console.readline());
Console.writeline("enter the values for the matrix");
For (int i = 0; i < m; i++)
For (int j = 0; j < n; j++)
X[i,j] = int.parse(console.readline());
Console.writeline("the values of the matrix is ");
For (int i = 0; i < m; i++)
{
For (int j = 0; j < n; j++)

Console.write(x[i,j]+" ");
Console.writeline(" ");
}

}
}
Jagged array :
It is an array of arrays.
Jagged array is also a type of multidimensional array. Jagged arrays
contain some number of inner arrays. Each of which may have unique
upper limit.
Class program
{
Static void main(string[] args)
{
Int[][] x = new int[5][];
For (int i = 0; i < x.length; i++)
X[i] = new int[i + 7];
For (int i = 0; i < 5; i++)
{
Console.write(x[i].length+"\t");
For (int j = 0; j < x[i].length; j++)
Console.write(x[i][j] + " ");
Console.writeline();
}

}
}

Class program
{
Static void main(string[] args)
{

Int[][] x = new int[5][];


Console.writeline(x.length);
For (int i = 0; i < x.length; i++)
X[i] = new int[i + 2];
For (int i = 0; i < 5; i++)
{
For (int j = 0; j < x[i].length; j++)
X[i][j] = int.parse(console.readline());
Console.writeline();
}
For (int i = 0; i < 5; i++)
{
Console.write(x[i].length+"\t");
For (int j = 0; j < x[i].length; j++)
Console.write(x[i][j] + " ");
Console.writeline();
}

}
Nullable types:
To define a nullable type , the question mark symbol is suffixed to
underlying the data type.
It is applied to value types or array of value types.
Nullable types represent all the types plus the value null.

Class program
{
Static void main(string[] args)
{
Int ?Nullableint =null ;
Double? Nullabledouble =null;
Bool? Nullable = null;
Char? Nullablechar = null;
Int?[] arrayofnullableints = new int?[10];
Console.writeline(nullableint);
Console.writeline(nullabledouble);
Console.writeline(nullable);
Console.writeline(arrayofnullableints);
Console.writeline(nullablechar);
Nullableint = 200;
Console.writeline(nullableint);
Bool? X = null;
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
Int? Nullableint = 100;
Double? Nullabledouble = 23.44;
Bool? Nullable = null;
Char? Nullablechar = 'a';
Int?[] arrayofnullableints = new int?[10];
Console.writeline(nullableint);
Console.writeline(nullabledouble);
Console.writeline(nullable);
Console.writeline(arrayofnullableints);
Console.writeline(nullablechar);
Nullableint = 200;
Console.writeline(nullableint);
}
}

Nullable data types can be usefull when interacting with databases.


To check the columns in a table are empty.

Class databasereader
{
Public int? Numericvalue;
Public bool? Boolvalue ;
Public int? Getintfromdatabase()
{
Return numericvalue;
}
Public bool? Getboolfromdatabase()
{
Return boolvalue;
}
}

Class program
{
Static void main(string[] args)
{
Databasereader obj = new databasereader();
Int? X = obj.getintfromdatabase();
Console.writeline(x);
Bool? Z = obj.getboolfromdatabase();
Console.writeline(z);
}
}

Class databasereader
{
Public int? Numericvalue;
Public bool? Boolvalue =true;
Public int? Getintfromdatabase()
{
Return numericvalue;
}
Public bool? Getboolfromdatabase()
{
Return boolvalue;
}
}
Class program
{
Static void main(string[] args)
{
Databasereader obj = new databasereader();
Int? X = obj.getintfromdatabase();
Console.writeline(x);
Bool? Z = obj.getboolfromdatabase();
Console.writeline(z);
If (z == null)
Console.writeline("not defined");
Else
Console.writeline(z);
}
}

?? Operator:
This operator allows the user to assign a value to a nullable type if the
retrieved value is null.

Class databasereader
{
Public int? Numericvalue;
Public bool? Boolvalue;
Public int? Getintfromdatabase()
{
Return numericvalue;
}
Public bool? Getboolfromdatabase()
{
Return boolvalue;
}
}
Class program
{
Static void main(string[] args)
{
Databasereader obj = new databasereader();
Int? X = obj.getintfromdatabase()??125;
Console.writeline(x);
Bool? Z = obj.getboolfromdatabase()??False ;
Console.writeline(z);
If (z == null)
Console.writeline("not defined");
Else
Console.writeline(z);
}
}

Namespace:
It is a collection of classes.
Using:
It is the directive used to use the namespace.

Using system;

Class employee
{
Private string fullname;
Private int empid;
Private float currpay;
Public employee()
{
}
Public employee(string fullname, int empid, float currpay)
{
This.fullname = fullname;
This.empid = empid;
This.currpay = currpay;
}
Public void givebonus(float amount)
{
Currpay += amount; //currpay =currpay +amount ;
}
Public void display()
{
Console.writeline(fullname);
Console.writeline(currpay);
Console.writeline(empid);
}
}

Class program
{
Static void main(string[] args)
{
Employee e1 = new employee("harsha", 100, 25000);
Employee e2 = new employee("kumar", 200, 1200);
E1.givebonus(500);
E2.givebonus(600);
E1.display();
E2.display();
}
}

Pillars of oops:
 Encapsulation
 Inheritance
 Polymorphism

Encapsulation:
It hides the unncessary implementation details from the object user.
It also specifies the data protection.
Inheritance:
Drawing the properties from the existing to the newly defined class.
It allows the user to extend the behaviours of base class to derived class.

This illustrates "is-a " relationship. ( it can also be called as classical


inheritance)

(multilevel inheritance specifies "is-a" relationship)

 Containment / delegation model ( " has - a " relationship)

This specifies , a class can define a member variable of another class and
expose the functionalities to outside world.

Here ,there are two concepts. Contained and containing class.

Radio --------> contained class


Car ----------> containing class.

Note: both classes are independent.

Ex:
Public class radio
{
Public void power(bool turnon)
{
Console.writeline(turnon);
}
}
Public class car
{
Private radio r = new radio();
Public void turnonradio(bool onoff)
{
R.power(onoff);
}
}
Class program
{
Static void main(string[] args)
{
Car viper = new car();
Viper.turnonradio(true);
}
}

Polymorphism:
Class shapes
{
Public void draw()
{
Console.writeline("specifies shapes");
}
}
Class circle :shapes
{
Public void draw()
{
Console.writeline("circle class method");
}
}
Class hexagon :shapes
{
Public void draw()
{
Console.writeline("hexagon class method");
}
}

Class program
{
Static void main(string[] args)
{
Shapes[] obj = new shapes[3];
Obj[0] = new circle();
Obj[1] = new hexagon();
Obj[2] = new circle();
Foreach (shapes s in obj)
S.draw();
}
}
Class shapes
{
Public virtual void draw()
{
Console.writeline("specifies shapes");
}
}
Class circle :shapes
{
Public override void draw()
{
Console.writeline("circle class method");
}
}
Class hexagon :shapes
{
Public override void draw()
{
Console.writeline("hexagon class method");
}
}

Class program
{
Static void main(string[] args)
{
Shapes[] obj = new shapes[3];
Obj[0] = new circle();
Obj[1] = new hexagon();
Obj[2] = new circle();
Foreach (shapes s in obj)
S.draw();
}
}

Form of encapsulation services:


Accessor (get) and mutator (setter) methods:
Accessor method is used to access the data . Mutator is used to set the
data.

Class employee
{
Private string fullname;
Public string getfullname()
{
Return fullname;
}
Public void setfullname(string s)
{
Fullname = s;
}
}

Class program
{
Static void main(string[] args)
{
Employee e1 = new employee();
E1.setfullname("harsha");
String x =e1.getfullname();
Console.writeline(x);
}
}

Another form of encapsulation :


Rather than invoking getter and setter methods to set and get the data,
user can invoke public field.

Using get block and set block


Class employee
{
Private int empid;
Private float currpay;
Private string fullname;
Public int id
{
Get //get block
{
Return empid;
}
Set //set block
{
Empid = value;
}
}
Public string fullname
{
Get
{
Return fullname;
}
Set
{
Fullname =value ;
}
}
Public float pay
{
Get
{
Return currpay;
}
Set
{
Currpay=value;
}
}

Class program
{
Static void main(string[] args)
{
Employee e1 = new employee();
E1.id =100;
E1.fullname ="abc";
E1.pay =17000;

Console.writeline(e1.id + " " + e1.name + " " + e1.pay);


}
}

Using constructor:

Class employee
{
Private int empid;
Private float currpay;
Private string fullname;
Private int age;
Public employee(int id, string name, int pay)
{
Empid = id;
Fullname = name;
Currpay = pay;
}

Public int id
{
Get
{
Return empid;
}

}
Public string name
{
Get
{
Return fullname;
}

}
Public int age
{
Get
{
Return age;
}
Set
{
Age = value;
}
}

Public float pay


{
Get
{
Return currpay;
}

}
}

Class program
{
Static void main(string[] args)
{
Employee e1 = new employee(100, "harsha", 17000);
E1.age = 24;
Console.writeline(e1.id + " " + e1.name + " " + e1.pay+"
"+e1.age );
}
}

Static properties:
Class employee
{
Private static string companyname;
Public static string company
{
Get
{
Return companyname;
}
Set
{
Companyname = value;
}
}
}
Class program
{
Static void main(string[] args)
{
Employee.company ="abc";
Console.writeline(employee.company);
}
}

Note: when the public field is static , then the data member should also be
static

Class employee
{
Private static string companyname;
Public string company
{
Get
{
Return companyname;
}
Set
{
Companyname = value;
}
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new employee();
E1.company = "xxx";
Console.writeline(e1.company);
}
}

Second pillar : inheritance:


Public class employee
{
Public string name;
Public int empno;
Public string name
{
Set
{
Name =value ;
}

Get
{
Return name ;
}

}
Public int empno
{
Set
{
Empno =value ;
}
Get
{
Return empno;
}

}
Class salesperson : employee
{
Public int numbofsales;
Public int nsales
{
Set
{
Numbofsales =value ;
}
Get
{
Return numbofsales ;
}
}

Class program
{
Static void main(string[] args)
{
Salesperson s = new salesperson();
S.name = "harsha";
S.empno = 100;

S.numbofsales = 25;
Console.writeline(s.empno + " " + s.name + s.numbofsales);

}
}
}

Class resume
{
Protected int age;
Protected string name;
Public resume(int a, string s)
{
Age = a;
Name = s;
}
}
Class resume1 : resume
{
Protected string qual;
Protected int exp;
Public resume1(int x, string y, string z, int p)

: base (x,y) //invoking base class constructor


{
Qual =z;
Exp=p;
}
Public void display()
{
Console.writeline(age + " " + name + " " + qual + " " + exp);
}

}
Class program
{
Static void main(string[] args)
{
Resume1 r = new resume1(24, "harsha", "be", 2);
R.display();
}
}
Preventing inheritance: (sealed classes)
The class which cannot be further sub classed.
It can be done by using sealed keyword.

Class a
{
Public void check()
{
Console.writeline("base class function");
}
}
Sealed class b : a
{
Public void check()
{
Console.writeline("b class fun");
}
}

Containment / delegation: (has-a relationship)


Class first
{
Public void display()
{
Console.writeline("this is first class method");
}
}
Class second
{
Protected first f = new first();
Public void accept()
{
F.display();
}
}

Class program
{
Static void main(string[] args)
{
Second s = new second();
S.accept();

}
}

Class first
{
Public int display()
{
Return 100;
}
}
Class second
{
Protected first f = new first();
Public int accept()
{
Return f.display();
}
}

Class program
{
Static void main(string[] args)
{
Second s = new second();
Int m = s.accept();
Console.writeline(m);

}
}

Public class first


{
Public double compute()
{
Return 100.0;
}
}
Public class employee
{
Protected first f = new first(); // f is contained object.
Public double getcost()
{
Return f.compute();
}
Public first verify
{
Get
{
Return f;
}
Set
{
F = value;
}
}
}

Class program
{
Static void main(string[] args)
{
Employee obj1 =new employee ();
Double d =obj1.verify.compute();
Double d1=obj1.getcost();
Console.writeline(d);
Console.writeline(d1);

}
}
Nested type definition:
The types such as enum , class,interface, struct or delegate) can be
defined with in the scope of the class or structure.
Public class outer
{
Public class inner
{
Public void display()
{
Console.writeline("inner class method");
}
}

Class program
{
Static void main(string[] args)
{

Outer .inner obj = new outer.inner ();


Obj.display ();
}
}
Public class outer
{
Public class inner
{
Public void display()
{
Console.writeline("inner class method");
}
Public enum enumdays // enumeration
{
Monday, tuesday, wednesday
}
}

Class program
{
Static void main(string[] args)
{

Outer .inner obj = new outer.inner ();

Outer.inner.enumdays e = outer.inner.enumdays.wednesday;
Console.writeline(e);
Obj.display ();

}
}
Third pillar of oops concept:
Polymorphism:

Polymorphism provides a way for sub class to customize how it implements


a method defined by its base class.

The base class wishes to define a emthod that may be overridden by a sub
class.
Public class employee
{
Float curpay;
Public virtual void givebonus(float amount)
{
Curpay = amount;
Console.writeline(curpay);
}
}
Public class salesperson : employee
{
Public override void givebonus(float amount)
{
Base .givebonus (amount );
Console.writeline("iam in salesperson");

}
}

Public class manager : employee


{
Public override void givebonus(float amount)
{
Base.givebonus(amount);
Console.writeline("iam in manager");
}

Class program
{
Static void main(string[] args)
{
Manager obj1 = new manager();
Obj1.givebonus(1000);
Salesperson obj2 = new salesperson();
Obj2.givebonus(2000);
}
}

Abstract class:
It is one which contains abstract method.
For the abstract class object cannot be created.
Abstract method has to be overridden in derived class.

Abstract class abc


{
Public void getdata()
{
Console.writeline("abc method");
}
Public abstract void display(); // abstract method
}
Class xyz : abc
{
Public override void display()
{
Console.writeline("abstrct method defined");
}
}
Class program
{
Static void main(string[] args)
{

Xyz obj = new xyz();


Obj.display();
Obj.getdata();

}
}

Abstract class can also contain only declared method( abstract method
only)

Abstract class abc


{
Public abstract void display();
}
Class xyz : abc
{
Public override void display()
{
Console.writeline("abstrct method defined");
}
}
Class program
{
Static void main(string[] args)
{

Xyz obj = new xyz();


Obj.display();

}
}

Abstract class can also contain virtual function.


It has to be overridden in derived class.

Abstract class shape


{

Public virtual void draw()


{
Console.writeline("draw of shape method");
}

}
Class circle : shape
{

Public override void draw()


{
Console.writeline("circle draw method");
}
}
Class hexagon : shape
{

Public override void draw()


{
Console.writeline ("hexagon draw");
}

Class program
{
Static void main(string[] args)
{
Hexagon hex =new hexagon ();
Hex.draw ();
Circle cir =new circle ();
Cir.draw ();
}
}

Member hiding:
It is opposite of method overriding.
It is used to hide the parent version.
(derived types implementation hides the parents version).

It uses the keyword "new" .


Public class first
{
Public new void display()
{
Console.writeline("base class member");
}
}
Public class second : first
{
New public void display()
{
Console.writeline("derived class member");
}
}
Class program
{
Static void main(string[] args)
{
Second s = new second();
S.display();
((first)s).display();
}
}
Casting :

Implicit casting:
Storing the derived type with in a base class reference.

Ex:
Employee e = new manager();

(assuming employee is base class and manager is derived class).

Object frank = new manager();


Manager mgr = (manager)frank; // explicit
casting

Employee e = new manager(); // implicit casting

Determine the type of employee :

Class employee
{
Protected int empno;
Public void getinfo()
{
Empno = 100;
}
}
Class manager : employee
{
Public void putinfo()
{
Console.writeline(empno);
}
}
Class sales:employee
{
Protected string name;
Public void getname()
{
Name = "abc";
}
}

Class x
{
Public static void output (employee e)
{
If (e is manager)
{
E.getinfo();
Console.writeline(e);

}
If (e is sales)
{
E.getinfo();
Console.writeline(e);
}

}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new manager();
Employee e2 = new sales();
X.output(e1);
}
}

Numerical cast :
Class program
{
Static void main(string[] args)
{
Int x = 100;
Byte b = (byte) x; // explict cast
Console.writeline(b);

Byte b1 = 30;
Int y = b1; //implicit cast
Console.writeline(y);
}
}

Partial type:
Partial modifier allow c# type acro multiple *.c file

Exception handling:
Bugs:
Putting an error on the part of the programmer.
Ex: fail to delete allocated memory. Resulting in memory leak. This is a
bug.

Error:
Errors are caused by the individual running the application.

Exception :
Exceptions are typically regarded as runtime anomolies.
Ex: dividing a number by zero.
Attempting to connecting to data base which is no longer exists.
The .net base class library defines numerous exceptions such as
 Formatexception
 Indexoutofrangeexception
 Filenotfoundexception

The role of .net exception handling:


.net platform provides a standard technique to send and trap runtime erors
.structured exception handling.

Excpeptions are objects that contain a human readable description of the


problem.
Exception is a runtime error that the program may encounter during the
execution of the program.

Atoms of the exception handling:


 A class type that represents the details of the exception that
occured.
 A member that throws an instance of the exception class to the caller.
 A block of code on the callers side that invokes the exception prone
member.
 A block of code on the callers side that will process the exception (
catch ) the exception.

The keywords used to throw and handle exceptions are try , catch, finally,
throw

All the user and system defined exceptions ultimately derive from
system.exception

Exceptions are thrown by the clr are called system exceptions.


System.systemexception base class represents the exceptions thrown
from the clr.

Systemexceptions are derive from system.systemexception, which in


turn derive from system.exception which derives from system.object
Application level exception:
These are derived from system.applicationexception
Creating user defined application specific exceptions.

Building custom exceptions :


The new class has to be derived from system.applicationexception

Processing multiple exceptions :


Namespace example1
{
Class program
{
Static void main(string[] args)
{
Try
{
Console.write("enter number1 : ");

Int a = int.parse(console.readline());

Console.write("enter number2 :");


Int b = int.parse(console.readline());

Int c = a / b;

Console.writeline(" {0} / {1} = {2}", a, b, c);


}

Catch (formatexception errorformat)


{
Console.writeline("error message : " +
errorformat.message);
Console.writeline("input only numbers in range 0 - 9
\nformat : number1 = 10 number2 = 20");
}

Catch (overflowexception erroroverflow)


{
Console.writeline("error message : " +
erroroverflow.message);
Console.writeline("input integer numbers in range {0} to
{1}", int.minvalue, int.maxvalue);

Catch (dividebyzeroexception errordivision)


{
Console.writeline("error message : " +
errordivision.message);
Console.writeline("denominator value cannot be equal to
zero");
}
Catch (exception errorglobal)
{
Console.writeline("error :\n : {0}", errorglobal.tostring());
}

}
}
}

Finally block :
Finally block is to ensure that set of code statements will always execute.
Whether the exception is thrown or not.
Using system;
Using system.collections.generic;
Using system.text;

Namespace example4
{
Class program
{
Static void main(string[] args)
{
Try
{
Console.write("a = ");
Int a = int.parse(console.readline());
Console.write("b = ");
Int b = int.parse(console.readline());

Int c = a / b;
Console.writeline(" {0} / {1} = {2}", a, b, c);

Catch (dividebyzeroexception errordivision)


{
Console.writeline("error message : " +
errordivision.message);
}
Catch (overflowexception erroroverflow)
{
Console.writeline("error message : " +
erroroverflow.message);
}
Catch (formatexception errorformat)
{
Console.writeline("error message : " +
errorformat.message);
}
Catch (exception errorglobal)
{
Console.writeline("error : \n" + errorglobal);
}

Finally
{
Console.writeline("executing finally block");
}
}
}
}

Rethrowing the exception :


This can be done by using the keyword "throw" in the catch block.
Try
{

Catch(exception e)
{
Throw e;
}

Inner exception :
Encountering an exception while processing another exception.

Ex:
Catch(sampleexception e)
{
Try
{
}
Catch(exception error)
{

Throw new sampleexception (e1 )


}

Basics of garbage collection:


The grabage collector is the background process running with in the
program. It is present with in all .net applications.
When the object goes out of scope or if the object is assigned to null then
the garbage collector will mark the object need to be cleaned up.

Finalization type :
A class could contain finalizer, which executes when the object is
destroyed.

Protected void finalize()


{
Base.finalize() ; // clean external resources.
}

Note: the method finalize() is called by the .net framework.\

Guidelines for the finalize method:


 Only implement finalize on objects that require finalization.
 Finalize method should be protected (not public)
 Finalize method should not be called directly on an object other than
objects base class.

Dispose :
Instead of declaring a finalizer, the dispose method can be used.
If the obejct is cleaned up by using dispose method or close method , then
it indicates to the runtime that the object is no longer needed finalization
by calling gc.suppressfinalize() .

Public void dispose()


{
Gc.suppressfinalize(this);
}

Building an ad hoc destruction method:

The system resources will be released when the object is no longer


needed.

To determine this , the following programming is given.

It uses a statement called "using" .

Public class sample : idisposable


{
Public void dispose()
{
Console.writeline("dispose called");
Gc.suppressfinalize(this);

}
~sample()
{
Dispose();
}
}

Class program
{
Static void main(string[] args)
{
Sample s = new sample();
Using (s )
{
Console.writeline("before leaving using statement");
}
Console.writeline("after leaving using statement");
}

Note:after exiting the using statement , dispose method is executed. Before


leaving this method ,
The gc.suppressfinalize() method is invoked. This informs the garbage
collector to not invoke the object destructor.

Garbage collection optimizations:


 Weak reference
 Generations

Weak references:
Weak references are means of performance enhancement. Used to reduce
the pressure place on the managed heap by large objects.

When a root points to an object it is called a strong reference


When an object has a weak reference to it, it basically means that if there
is a memory requirement and the garbage collector runs, the object can
be collected and when the application later attempts to access the object,
the access will fail.
On the other hand, to access a weakly referenced object , the application
must obtain a strong reference to the object. If the application obtains the
strong reference before the garbage collector collects the object, then the
gc cannot collect the object because a strong reference to the object exists.

The managed heap contains two internal data structures to manage weak
references.
Short weak reference table and long weak reference table.

Weak reference are of two types:


 A short weak reference does not track resurrection.
That is the object which has a short weak reference to itself is
collected immediately without running its finalization method.

Long weak reference tracks resurrection.


That is the garbage collector collects object pointed to by the long weak
reference table only after determining that the objects storage is
reclaimable. If the object has a finalize method, the finalize method is been
called and the was not resurrected.

An example to show how garbage collector runs:


 Garbage collector builds a graph of all the reachable objects. Ex:
b,c,e,g
 The garbage collector scans the the short weak reference table . If a
pointer in the table refers to an object that is not part of the graph ,
then the pointer identifies an unreachable object and the slot in the
short weak reference table is set to null. Ex: d is set to null. Because
it is not part of the graph.
 Garbage collector scans finalization queue. If a pointer in the queue
refees to an object that is not part of the graph, then the pointer
identifies an unreachable object and the pointer is moved from the
finalization queue to the freachable queue. At this point the object is
added to the graph. Since the object is considered reachable. Ex:
a,d,f are not included in the graph they are treated as reachable
objects .because they are part of the finalization queue. Finalization
queue thus gets emptied.
 The garbage collector scans the long weak reference table. If the
pointer in the table referes to an object that is not part of the graph
(which are objects pointed to by in freachable queue), the the pointer
identifies an unreachable object and the slot is set to null. Since
both the objects c and f are a part of the graph.
 The garbage collector compacts the memory,squeezing out the holes
left by the unreachable objects. In the ex: object h is the only
object that gets removed from the heap and its memory is reclaimed.

Three generations of garbage collector :


 Generation 0 : most recently created objects
 Generation 1 : mid life objects
 Generation 2 : the long term objects

Note: all the reference types will exist in one of these 3 generations.
They will firstly be allocated to gen 0, then moved to gen1 and gen 2
depending on their life time.

Generations of garbage collector:


Garbage collection cannot complete without stopping the entire program.
They can cause long pauses during the execution of the program.
Garbage collection pauses can also prevent programs from responding to
events quickly enough to satisfy the requirements of real time systems.

One feature of garbage collector that exists is to improve performance is


called generations.

Generational collectors group objects by ae and collect younger objects


more often than older objects.
When initialized , the managed heap contains no objects. All new objects
added to the heap can be said to be in generation 0 , until the heap gets
filled up which invokes garbage colelction.
As more objects are short lived, only a small percentage of young objects
are likely to survive their first collection.
Once the object survives then it gets promoted to generation 1. Newer
objects after gc can then be said to be in generation 0.
Garbage collector gets invoked next only when the sub-heap of generation
0 gets filled up. All objects in generation 1 that survive get promoted to
generation 2. All survivors in generation 0 also get promoted to
generation 1. Generation 0 contains no objects. But all newer objects
after gc go into generation 0.
Thus dividing the heap into generations of objects and collecting and
compacting younger generation objects improves the efficiency of the
garbage collection by reclaiming the amount of space from the heap .
System.gc type:
This controls the system garbage collector. A service that automatically
reclaims unused memory. The method in this class influence when
garbage collection is performed on an object and when resources
allocated by an object are released.

Properties in this class provide information about the total amount of


memory available in the system and the memory allocated to object.

The garbage collector tracks and reclaims objects allocated in managed


memory.

Garbage collector consist of following steps:


 The garbage collector searches for managed objects that are
referenced in managed code.
 Garbage collector tries to finalize objects that are not referenced.
 The garbage collector frees objects that are not referenced and
reclaims their memory.

Garbage collector does not recognize refeences to an object from


unmanaged code , and might free objects that are being used extensively
in unmanaged code unless explicitly prevented from doing so.

Executing garbage collector :


Try
{
System.gc.collect();
Messagebox.show("garbage collector running for all generations");
}
Catch(exception ex)
{
Messagebox.show(ex.stacktrace);
}

Class program
{
Static void main(string[] args)
{
Console.writeline("estimated bytes on heap {0}",
gc.gettotalmemory(false));
Console.writeline("{0} the object generations ",
gc.maxgeneration+1);
}
}

Interfaces :
Interface is nothing but a named collection of abstract members.

Interface members are all implicitly public.


Public interface abc
{
Void get();
}

Class a : abc
{
Public void get()
{
}

}
Note:
Interface must be listed after colon operator.
Syntax:
Class classname : interfacename

Implementing interface :

Interface xyz
{
Void get1();
}
Class p1 : xyz
{
Public void get1()
{
Console.writeline("interface method");
}
}
Class program
{
Static void main(string[] args)
{
P1 obj = new p1();
Obj.get1();

}
}

Multiple inheritance can be implemented by using interface.

Drawing the properties from only one class and implementing any number
of interfaces.

Note: while inheriting class and interface ,


The class must be listed first after the colon (: ) operator and then interface
name.

Class p1
{
Public void get1()
{
Console.writeline("this is class method");
}
}

Interface xyz
{
Void get2();
}
Class p2 : p1,xyz
{
Public void get2()
{
Console.writeline("interface method");
}
}

Class program
{
Static void main(string[] args)
{
P2 obj = new p2();
Obj.get1();
Obj.get2();

}
}

Abstract class abc


{
Abstract public void get();
Public void put()
{
Console.writeline("abstrac class method");
}
}
Class pqr : abc
{
Public override void get()
{
Console.writeline("defined");
}
}
Class program
{
Static void main(string[] args)
{
Pqr obj = new pqr();
Obj.get();
Obj.put();
}
}

Accessing interface members at object level:


Interface x
{
Void get();
}
Class abc : x
{
Public void get()
{
Console.writeline("defined in abc");
}
}
Class pqr : x
{
Public void get()
{
Console.writeline("defined in pqr");

}
}

Class program
{
Static void main(string[] args)
{
X x1 = new abc();
X1.get();
X1 = new pqr();
X1.get();

}
}

Accessing interface members at object level :


Interface abc
{
Int x { get;}

}
Class a : abc
{
Public int x
{
Get
{
Return 100;
}
}

}
Class program
{
Static void main(string[] args)
{
Abc obj;
A obj1 =new a();
Obj =(abc)obj1;
// obj.x = 200;
Console.writeline (obj.x);

}
}

Public class fc
{
Protected string data;
Public string data
{
Get
{
Return this.data;
}
Set
{
This.data = value;
}
}
}
Interface xyz
{
Bool validate();
}
Class mc : fc,xyz
{
Public mc()
{
Data ="checking";
}
Public bool validate()
{
Console.writeline (data);
Return true ;
}
}

Class program
{
Static void main(string[] args)
{
Mc obj = new mc();
Xyz x = (xyz)obj;
Bool success = x.validate ();
Console.writeline (obj.data );

}
}
Arrays of interface types :
Interface x
{
Void get();
}
Class abc : x
{
Public void get()
{
Console.writeline("defined in abc");
}
}
Class pqr : x
{
Public void get()
{
Console.writeline("defined in pqr");
}
}
Class program
{
Static void main(string[] args)
{
X[] x1 ={ new abc(), new pqr() };
For (int i = 0; i < x1.length; i++)
X1[i].get();
}
}
Explicit interface implementation:
Interface dimension
{
Float length();
Float width();
}
Class box : dimension
{
Float lengthinches, widthinches;
Public box(float length, float width)
{
Lengthinches = length;
Widthinches = width;

}
Float dimension.length()
{
Return lengthinches;
}
Float dimension.width()
{
Return widthinches;
}
}
Class program
{
Static void main(string[] args)
{
Box mybox = new box(10.0f,12.0f);
Dimension d = (dimension )mybox;
Console.writeline(d.length());
Console.writeline(d.width());
}
}

Interface dimension1
{
Float length();
Float width();
}
Interface dimension2
{
Float length();
Float width();
}
Class box : dimension1,dimension2
{
Float lengthinches, widthinches;
Public box(float length, float width)
{
Lengthinches = length;
Widthinches = width;

}
Float dimension1.length()
{
Return lengthinches;
}
Float dimension1.width()
{
Return widthinches;
}
Float dimension2.length()
{
Return lengthinches * 10.0f;
}
Float dimension2.width()
{
Return widthinches * 20.0f;
}

Class program
{
Static void main(string[] args)
{
Box mybox = new box(10.0f,12.0f);
Dimension1 d = (dimension1 )mybox;
Dimension2 d1 = (dimension2)mybox;

Console.writeline(d.length());
Console.writeline(d.width());
Console.writeline(d1.length());
Console.writeline(d1.width());

}
}

Interface hierarchi :
One interface can inherit other interface.

Interface abc
{
Void get();
}
Interface xyz: abc
{
Void put();
}
Interface a
{
Void get();
}
Interface b : a
{
Void put();

}
Class sample : b
{
Public void get()
{
Console.writeline("first interface method defined");
}
Public void put()
{
Console.writeline("second interface method defined");
}

}
Class program
{
Static void main(string[] args)
{
Sample s1 = new sample();
S1.get();
S1.put();
}

Interface a
{
Void get();
}
Class b : a
{
Public void get()
{
Console.writeline("interface method defined");
}
}
Class sample : b
{
Public new void get()
{
Console.writeline("first interface method defined");
}

}
Class program
{
Static void main(string[] args)
{
Sample s1 = new sample();
// s1.get();
// s1.put();
((a)s1).get ();

Interface a
{
Void get();
}
Interface b : a
{

}
Class sample : b
{
Public void get()
{
Console.writeline("first interface method defined");
}

}
Class program
{
Static void main(string[] args)
{
Sample s1 = new sample();
S1.get();
}
}
Exploring the system.collection name space:

This name space contains interfaces and classes that define various
collections of objects such as lists ,queues , bit arrays, hash tables and
dictionaries.

Class

 Arraylist dynamically sized array of objects . It implements


ilist , icollection interfaces.
 Hashtable represents a collection of key / value pairs that are
organized based on the hash code of the key. (
idictionary , icollection ,ienumerable ,icloneable)
 Queue represents first -in , first-out collection of
objects.(icollection ,
Icloneable ,ienumerable)
 Stack represents last-in first --out . (icollection ,
icloneable ,ienumerable)

Interfaces:
 Icollection defines size, enumerators and syncronization
methods.
 Icomparer exposes method to compare two objects.
 Idictionary represents a non generic collection of key / value
pairs.
 Ienumerable returns the ienumerator interface for a given object.
Supports simple
Iteration over a non generic collection.
 Ienumerator supports foreach style iteration over a non
generic collection.

Iconvertible interface :
Defines methods that convert the value of the implementing reference or
value type to a common language runtime type that has an equivalent
value.
This api is not cls-compliant.

Syntax:
Public interface iconvertible

The clr types are boolean, byte, int16,int32 , datetime,char etc


Ex:
If this interface is implemented on a boolean type , the implementation of
todatetime() method throws an exception because there is no meaningful
datetime equivalent to a boolean type.

The clr exposes this interface through convert class.


Note: clr also uses this interface internally.

Class complex : iconvertible


{
Double x, y;
Public complex(double a, double b)
{
X = a;
Y = b;
}

Public typecode gettypecode()


{
Return typecode.object;
}
Bool iconvertible.toboolean(iformatprovider provider)
{
If (x != 0.0 || y != 0.0)
Return true;
Else
Return false;
}
Double getdoublevalue()
{
Return math.sqrt(x * x + y * y);
}
Byte iconvertible.tobyte(iformatprovider provider)
{
Return convert.tobyte(getdoublevalue());
}
Char iconvertible.tochar(iformatprovider provider)
{
Return convert.tochar(getdoublevalue());
}
Short iconvertible.toint16(iformatprovider provider)
{
Return convert.toint16(getdoublevalue());
}

Long iconvertible.toint64(iformatprovider provider)


{
Return convert.toint64(getdoublevalue());
}
Int iconvertible.toint32(iformatprovider provider)
{
Return convert.touint32 (getdoublevalue());
}

Class program
{
Static void main(string[] args)
{
Complex m = new complex (4,7);
Display (m);
Display (convert .toboolean ());
Display(convert.tobyte ());
Display(convert.toint16 ());
Display (convert.toint64 ());
}
Static void display(object o)
{
Typecode t = type.gettypecode(o.gettype);
Switch (t)
{
Case typecode.boolean:
Console.writeline(m);
Break;
Case typecode.double:
Console.writeline(m);
Case typecode.int16:
Console.writeline(m);
Case typecode.int16:
Console.writeline(m);

Ienumerable and ienumerator interfaces:


Ienumerator interface is the base interface for all enumerators.
Enumerators only allo reading teh data in the collection.
Initialy , enumerator is positioned before the first element in the collection.
This interface has following members.

Property : current
Method : movenext
Method : reset.

Ienumerable :
This interface is an interface that has one method called getenumerator() .
This method supports simple iteration over collection.

Public class car


{
Public int currsp;
Public string name;
Public car(string n, int speed)
{
Name = n;
Currsp = speed;
}
Public override string tostring()
{

Return string.format("{0},{1}", name, currsp);


}
}
Public class dealer
{
Private car[] cararray;
Public dealer()
{
Cararray = new car[3];
Cararray[0] = new car("nano", 80);
Cararray[1] = new car("tata", 100);
Cararray[2] = new car("indica", 200);
}

Public ienumerator getenumerator()


{
Return cararray.getenumerator();
}

Class program
{
Static void main(string[] args)
{
Dealer d = new dealer();
Ienumerator i = d.getenumerator();
I.movenext();
Car mycar = (car)i.current;
Console.writeline(mycar.name);
Console.writeline(mycar.currsp);
}
}
}

Icloneable:
Cloning is to make an exact copy of an instance of a type.
It takes one of the two forms.

Shallow copy or deep copy

Shallow copy :
May be linked to data shared by both the original and copy.

Deep copy :
Contains the complete encapsulated data of the original object.

Class myvalue
{
Public int count ;
Public myvalue (int count)
{
This.count =count;
}
}
Class myobject : icloneable
{
Public myvalue contained;
Public myobject (int count )
{
This.contained =new myvalue (count );
}
Public object clone()

{
Console.writeline ("clone");
Return (new myobject (this.contained .count ));
}
}

Class program
{
Static void main(string[] args)
{
Myobject m =new myobject (100);
Myobject myclone =(myobject )m.clone ();
Console.writeline ("{0}{1}",m.contained .count ,myclone
.contained .count );
Myclone .contained .count =15;
Console.writeline ("{0}{1}",m.contained .count
,myclone.contained .count );

}
}
Icomparable interface :
This interface defines a comparison method to be implemented by a value
type or class.
This interface specifies a behaviour that allows an object to be sorted
based on some specified key.
Public class car:icomparable
{
Private int carid;
Public string name;
Private int currsp;
Int icomparable.compareto (object obj)
{
Car temp = (car)obj;
If(this.carid > temp.carid )
Return 1;
If(this.carid < temp.carid )
Return -1;
Else
Return 0;
}

Public int id
{
Get
{
Return carid;
}
Set
{
Carid = value;
}
}
Public car(string n, int speed, int id)
{
Carid =id;
Name =n;
Currsp =speed ;
}

Class program
{
Static void main(string[] args)
{
Car[] m = new car[5];
M[0] = new car("indica", 80, 20);
M[1] = new car("nane", 100, 10);
M[2] = new car("wagnor", 200, 30);
Foreach (car c in m)
Console.writeline("{0}{1}", c.id, c.name);
Array .sort (m );
 Foreach (car c in m)
Console.writeline ("{0}{1}", c.id,c.name );

}
}

Using system.collections;
Public class student
{
Private int rollno,marks;
Private string subject;
Public string subject
{
Get
{
Return subject;
}
Set
{
Subject = value;
}
}

Public int rollno


{
Get
{
Return rollno;
}
Set
{
Rollno=value;
}
}
Public int marks
{
Get
{
Return marks;
}
Set
{
Marks =value;
}
}
Public student(string s,int m,int rn)
{
Rollno =rn;
Subject =s;
Marks =m;
}
}

Public class student1 : icomparer


{
Public student1()
{
}
Int icomparer.compare(object o1, object o2)
{
Student s1 = (student)o1;
Student s2 = (student)o2;
Return string.compare(s1.subject , s2.subject );
}
}

Class program
{
Static void main(string[] args)
{
Student[] check = new student[3];
Check[0] = new student("maths", 75, 100);
Check[1] = new student("maths", 85, 200);
Check[2] = new student("maths", 90, 300);
Array .sort (check,new student1());
Foreach( student st in check )
Console.writeline ("{0}\t\t{1}",st.rollno ,st.marks );

}
}

The role of command line compiler:


The csc.exe executable is located in the microsoft \net \
framework\<version?\> folder under the system directory . Its location may
vary.

User can invoke c#compiler by the typing the name of its executable file
(csc.exe) on the command line.
If the user uses visual studio command prompt , all the ncessary
environment variables are set for the user.
If the user does not use visual studion prompt then vsvars32.bat to set the
appropriate environment variables to support command line builds.

Building c# application using csc.exe :


C# compiler uses the following rules when interpreting arguments given on
the operating system command line.

 Arguments are delimited by white space ( space or tab)


 The caret operator (^) is not recognised as an escape character or
delimiter. The character is completely handled by the command line
parser in os before being passed to the argv array in the program.
 A string surrounded by doulbe quotation marks is interpreted as a
single argument.
 A double quotation mark preceded by backslash (\) is interpreted
as a literal double qoutation mark.
 If an even number of backslashes is followed by a double quotation
mark, one backslash is placed in the argv array for every pair of
backslashes, and the double quotation mark is interpreted as a string
delimiter.
 If an odd number of backslashes is followed by a double quotation
mark, one backslash is placed in the argv array for every pair of
backslashness, and the double quotation mark is "escaped" by the
remaining backslash, causing a literal double quotation mark (") to be
placed in argv.

The flags passed to csc.exe as a command line parameters are :


 /out ------------csc/out: my.exe file.cs
 /target :library -------csc/ target:library file.cs
 /target:exe ----csc/target:exe file.cs
 /target:module
 /target:winexe
Command line debugger :
This tool provides dozens of options that allow user to debug the
assembly .

The commmand line flags are as follows:


B[reak]-------> break points
Del[ete]-----> remove break points
Ex[it] --------> exit the debugger
P[rint]-------> print all loaded variables
G[0]---------> continue debugging

The debugging at the command line is as follows:


Csc @file.isp/debug

 Call back interfaces:


Interfaces can be used as a call back mechanism.
It enables the objects engage in a two way conversation using a common
set of members.
Interface a
{
Void display();
}
Class b : a
{
Public int x,y;
Public b(int m, int n)
{
X = m;
Y = n;
}
Public void display()
{
Console.writeline("interface method");
Console.writeline(x + " " + y);
}
}

Class c
{
Arraylist obj = new arraylist();
Public void putdata(a a1)
{
Obj.add(a1);
Foreach (a p in obj)
P.display();
}
Public void put(a a1)
{
// obj.remove(a1);
}
}
Class program
{
Static void main(string[] args)
{
B b1 = new b(100, 200);
C c1 = new c();
B1.display();
C1.putdata(b1);
C1.put(b1);

}
}
DELEGATES

DELEGATES ALLOWS TO CREATE A VARIABLE THAT “POINTS” TO A METHOD. THE


USER CAN USE THIS VARIABLE

AT ANY TIME TO INVOKE THE METHOD. DELEGATES HELPS TO WRITE FLEXIBLE


CODE THAT CAN BE

REUSED IN MANY SITUATIONS . THEY’RE ALSO THE BASIS FOR EVENTS

THE FIRST STEP WHEN USING A DELEGATE IS TO DEFINE ITS SIGNATURE . A


DELEGATE VARIABLE CAN

POINT ONLY TO A METHOD THAT MATCHES ITS SPECIFIC SIGNATURE. IN OTHER


WORDS, IT MUST HAVE THE

SAME RETURN TYPE AND THE SAME PARAMETER TYPES

DELEGATES: A DELEGATE IS A FUNCTION POINTER THAT ALLOWS TO INVOKE A


PROCEDURE INDIRECTLY .

DELEGATES ARE THE FOUNDATION FOR .NET EVENT HANDLING

Public delegate void displaydelegate(string msg);

Class program
{
Static void main(string[] args)
{
// instantiation
Displaydelegate del = new displaydelegate(displaymessage);
//invoke a delegate
Del("i was called by a delegate");
}

Static void displaymessage(string msg)


{
Console.writeline("message : " + msg);
}
}

Public delegate void display(int x); // declaration

Class program
{
Static void main(string[] args)
{
Display a = new display(dis);
A(100);
}
Static void dis(int b)
{
Console.writeline(b);
}
}

You might also like