Awp Unit-1 Notes
Awp Unit-1 Notes
UNIT – I
At the heart of Microsoft .NET is the .NET Framework, consisting of the common
language runtime and the class libraries.
These two components provide the execution engine and programming APIs for
building .NET applications.
Applications compiled for the .NET Framework are not compiled directly to native
code. Instead, they are compiled to an intermediate language called Microsoft
Intermediate Language (MSIL).
When an application is run for the first time, the common language runtime just-
in-time compiler compiles the MSIL code into native code before it is executed.
The common language runtime is more than a simple JIT compiler; it is also
responsible for providing low-level execution services, such as
garbage collection,
exception handling,
security services, and
runtime type-safety checking.
The .NET Framework also includes a set of classes for building applications that
run on the common language runtime.
These class libraries provide rich support for a wide range of tasks, including data
access, security, file IO, XML manipulation, messaging, class reflection, XML Web
services, user-interface construction, text processing, ASP.NET, and Microsoft
Windows services.
The most unique attribute of the .NET Framework is its support for multiple
languages.
The various components of the .Net framework 3.5. The following table describes the
components of the .Net framework 3.5 and the job they perform:
Common Language Runtime:
It is built around CTS. It performs runtime tasks like memory management and garbage
collection.
Base Class Libraries:
It is a rich set of functional base classes.
Extended Class Libraries:
Extended from base class libraries and designed to make it easier and faster to develop
a specific application.
CLS: (Common Language Specification)
It defines requirements for .net languages. It contains the specifications for the .Net
supported languages and implementation of language integration.
CTS: (Common Type System)
It provides guidelines for declaring, using and managing types at runtime and cross-
language communication.
The building blocks are web services themselves, so they can operate as stand-
alone components, or in collaboration with other components.
As web services, they are programmable, and can be easily called from a
custom application.
In contrast, ActiveX controls must be included within a Windows Application at
design time, and compiled directly into the runtime executable.
The .NET building block services will include:
• Authentication-builds on Microsoft’s passport and Windows authentication
technologies.
• Enables developers to authenticate a user behind-the-scenes, and give them
access to private content without bothering them to log in manually every
time they access a new application
• This authentication service will be available in the future Operating System,
code named Blackcomb.
• Notification and Messaging-provides integrated messaging capabilities for any
device, including instant messaging and e-mail.
• Directory and Search – director y search services, for locating people and
finding information.
• Calendar- This service provides time management and scheduling services for
your application.
• XML store-provides an addressable location on the Internet for storing data.
The data is stored as XML, and is delivered using SOAP. XML data stores
provide you with a single data store that can be accessed by all of your devices.
Class Libraries:
• The .NET framework classes are similar in concept to MFC, namely, they
provide developers with access to a wide range of system services without
having to do a lot of coding.
• The framework classes are organized into namespaces, which organize classes
into a hierarchical structure of related groups. For example, the System. Data
namespace contains a set of classes that provide data access functionality.
• The .NET framework provides classes at different levels of abstraction. At the
lowest level, the base class library provides a rich set of base classes that give
you easy access to Windows API functionality.
• Extended Class Libraries are nothing but abstracted classes that are focused
on one aspect of development: ASP .NET (For web services), ADO .NET (For
data access), XML (to parse and manipulate documents) and Windows Forms
(for windows based applications).
• CLS defines the requirements for .NET languages.
CTS defines standard, object oriented types and value types that are
supported by all .NET programming languages.
The CTS standards are what allow .NET to provide a unified programming
model, and to support multiple languages.
A CTS is the first prerequisite to allowing languages to interoperate.
This is easy to understand, if you consider that languages can only
interoperate if they are based on the same system of types.
In the past, type discrepancies have caused many interoperability problems,
particularly for VB developers.
So, CTS is an important new feature in the .NET framework. The CTS
must support a range of languages, some of which are object-oriented,
and some of which are not. Much has been made of the fact that
COBOL is now a first class .NET language. COBOL is a procedural
language, not an object-oriented one. The CTS provides two main types:
• Value Types
• Reference Types
Value types are simple data types that roughly correspond to simple bit
patterns like integers and floats.
In .NET, a value type derives from the System. Object amespace, and
supports an interface that provides information about the kind of data that
is stored, as well as the data value.
They are useful for representing simple data types, and nay not-object user
defined type, including enumerations.
They are known as exact types which mean that they fully describe the
value they hold.
Reference types are also derived from the system.
Object namespace, and may hold object references.
They are self typing, which means that they describe their own interface.
They are very specific to the type of object you are assigning.
Once the reference is assigned, you expect to query the object reference
according to what its interface provides.
Type Safety:
The CTS promotes type safety, which in turn improves code stability.
In .NET, type safety means that type definitions are completely known, and
cannot be compromised.
The CTS ensures that object references are strongly typed.
It checks whether the array index out of range or not, whether the
arithmetic exceptions are handled properly or not etc.
Meta Data is organized information that the CLR uses to provide compile
time and runtime services, including:
NET components are self describing, because the Meta Data is stored as part of
the compiled component known in .NET as an assembly. Combine this with the
fact that .NET components do not require windows registry entries, and you can
immediately appreciate why deployments are so much easier in .NET.
reflection
designers
debugger
profiler
Proxy generator
Schema serialization
Type Other IL Generator
Browser Compilers
The purpose of the NET framework is to define standards that makes it easier
it easier to write robust, secure and reusable code. The NET framework extends this
concept by allowing any language to participate in the framework; so long as it
conforms to the specifications embodied by the common Type System and the common
Language Specification.
The common language Specification (CLS) defines conventions that languages
must support in order to be interoperable within NET. The CLS defines rules that range
from naming conventions for interface members, to rules governing method
overloading.
In order to provide interoperation, a CLS- compliant language must obey the
following conventions:
Public identifiers are case- sensitive.
Language must be able to resolve identifiers that are equivalent to their
keywords.
Stricter overloading rules; a given method name may refer to any number
of methods, as long as each one differs in the number of parameters, or
argument types.
1. Simplify Development
• Define standards that promote code reuse
• provide a broad range of services, including memory management and
garbage collection
2. Simplify application deployment
• Components use meta data instead of registration
• support side-by-side, multiple component versions
• command-line deployment(Xcopy) and uninstall(DEL)
3. support development languages
• provide rich base classes for developer tools and languages
4. support multiple languages
• define CTS that are used by all .NET languages
5. enable convergence of programming models
• Build languages and tools on a common framework. For example, ASP .NET,
VB .NET, and C# have access to the same base classes.
• The CLR provides a number of runtime support services using the VES. The VES is
responsible for implementing and enforcing the CTS. The VES is designed to run
managed code, that is, code that supports the CTS. The execution engine uses
Meta data information to understand the structure of the components.
It is the standard for components developed by Microsoft. The assembly may or may
not contain exe file that is it can be .exe file or dynamic link library file (.dll). Main
component of assembly contains the definition of type’s versioning information for the
type metadata and manifest. The assembly can be used by single or multiple application.
There are 2 types assembly in dot net.
Private
Shared
1. Private assembly:- they are simple and used by single application & stored in the
application directory. This are used to deploy language specific resource and it
works in side by side execution. Because the application has a separate product id
for each language & installs satellite assembly in a language specific sub directory
for each language.
Components of Assembly:
Assembly manifest :-
The following illustration show the different ways to manifest can be stored.
File1.dll
manifest File2.dll Graphics.jpg Logo.bmp
manifest
The following table shows the information contain in the assembly manifest.
Information Description
Assembly name A text string specifying the assembly
name.
Version number A major & minor version number & a
revision & build number. The common
language runtime uses this no. To
nenforce version policy.
Culture Information on the culture or language
the assembly supports the informayion
should be use only to designate and
assembly as a satellite assembly
containing culture or language specific
information.
Strong name Information The public key from the publisher if the
assembly has been given a strong
name.
The garbage collector is a tool for memory management provided by dot net framework.
It runs in low priority thread and checks for those objects which are not referenced
dynamically allocated memory space.
If it finds some data that is no longer needed it frees up memory & returned back
to the OS so that it can be used by other programs
Garbage collector frees the programmer from keeping track of un-referenced
data.
Garbage collector provides explicit memory management & manages memory
leaks.
Garbage collector checks how objects are arranged in memory and identifies all
those object that can be used by the running programs.
Garbage collector marks this object as live. If they have reference once all of these
live objects are known. Any other objects can be declared and the space can be
reuse for new objects
Dot net reduces memory so that there ios no gap & free memory is always
available at the end of the heap.
When a garbage collection start. It looks at a set of references called ‘GCroot’ . it
contains references to objects created by the program.
When compiling to managed code the compiler translates your source code into
Microsoft intermediate language (MSIL.), which a CPU independent set of instructions
that can be efficiently converted to native. MSIL includes instruction for loading, storing,
initializing & calling method on objects as well as instruction for arithmetic & logical
operation control flow, direct memory access, Exception handling & other operations.
Before code can be run, MSIL must be converted to a CPU specific code just-in-time (JIT)
compiler. Because the common language runtime supplies one or more JIT compilers for
each computer architecture it supports. The some set of MSIL can be JIT compiled run
on an supported architecture.
When a compiler produces MSIL, it also produces metadata describes the types in
your code including the definition of each type the signature of each types. Members,
the members that your code references & other data that the runtime uses at execution
time. The MSIL & metadata are contained in a portable exe file.
JIT compilation takes into account the fact that save code might never get called
during execution rather than using time & memory to convert all the MSIL in a PE file to
native code, it converts the MSIL as needed during execution & stores the resulting
native code so that it is accessible for subsequent calls the loader creates & attaches a
stab to each of a types method when the type is loaded on the initial call to the method,
the stab passes control to the JIT compiler which converts the MSIL for that method info
native code & modifies the stab to direct execution to the location of the native code.
Although C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language. It has strong resemblance with Java,
it has numerous strong programming features that make it endearing to a number of
programmers worldwide.
Following is the list of few important features of C#:
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows
Namespace are C# program element designed to help you organize your programs. They
also provide assistance in avoiding name classes between two set of code.
Implementing Namespace in your own code is a good habit because it is likely to save
you from problems later when you want to reuse some of your code. For example :- if
you create a class named console you would need to put it in your own namespace to
ensure that there wasn’t any confusion about when the system console class should be
used. Generally it would be a bad idea to create a class named console.
The types of data that a variable contain is called Datatype. A Datatype is a classification
of things that share similar type of qualities or characteristics or behaviour .
C# strongly typed language so every variable and object must have a type.
Value Type
Value type variables can be assigned a value directly. They are derived from the class
System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which
stores numbers, alphabets, and floating point numbers, respectively. When you declare
an int type, the system allocates memory to store the value.
The following table lists the available value types in C# 2010:
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method. The expression sizeof(type) yields the storage size of the object or
type in bytes.
For example if you type
Console.WriteLine(sizeof(int)),
you will get the output as 4, the bytes occupied by an integer.
Reference Type
The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference
types can refer to a memory location. If the data in the memory location is changed by
one of the variables, the other variable automatically reflects this change in value.
Example of built-in reference types are:
object,
dynamic, and
string.
Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System
(CTS). Object is an alias for System. Object class. The object types can be assigned
values of any other types, value types, reference types, predefined or user-defined
types. However, before assigning values, it needs type conversion.
Example:
int m=100;
object ob=m;// we have created a box named ob and thus initiated boxing action.
object ob= (object) m //Explicit way of boxing which is optional
int num= (int) ob;// Unboxing
Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time. Dynamic types are similar to object
types except that type checking for object type variables takes place at compile time,
whereas that for the dynamic type variables takes place at run time.
For Example
dynamic dy=200;
String Type
The String Type allows you to assign any string values to a variable. The string type is an
alias for the System.String class. It is derived from object type. The value for a string
type can be assigned using string literals in two forms: quoted and @quoted.
For example,
String str="String handling";
Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have
the same capabilities as the pointers in C or C++.
Pointers are supported to some extent by .NET. It considers the instructions as unsafe
and we have to include them under unsafe block.
For Example,
unsafe{
char *c; }
Managed code is simply code that runs under the CLR with its common types, error
handling, debugging, and memory management. Even managed code can be unsafe and
being unsafe is more than just pointer specific. For example, the following C# code is
managed but unsafe:
Unsafe
{
Console.WriteLine(“Datetime size in
bytes”,sizeof(DateTime));
Console.WriteLine(“Short size in bytes”,sizeof(short));
Console.WriteLine(“int size in bytes”,sizeof(int));
Console.WriteLine(“long size in bytes”,sizeof(long));
}
• The C# code used the sizeof keyword will only compile if placed in an unsafe block. At
present the DateTime structure is 8 bytes. in some future version of .NET this
structure could be 12 bytes. this would mean that all the code compiled with the
present version of .NET would be invalid.
• Unsafe does not refer to present tense behavior but is a warning. it enables the
developers to use good and safe coding practices.
• If we use the stack, to print the DateTime, such a structure is unsafe, because this
data is placed on the stack. If this value goes out of scope, the stack location being
pointed to could change; this would result in unpredictable behavior.
• It is possible to allocate data on the stack using C#’s stackalloc keyword. But it cannot
be used to create reference types. Using stackalloc is unsafe, because if buffer went
out of scope, the contents of the stack could be unknown and would lead to
unpredictable behavior.
When one type of is assigned to another type of variable an implicit type conversion will
take place automatically if
When this two condition are met a widening conversion takes place. For example the int
type is always large enough to hold all valid byte values and both int and byte are
compatible integer types so an implicit conversion can be applied. For widening con
versions the numeric keys including integer and floating point type are compatible with
each other.
Casting Incompatible types
Although the implicit type conversion are helpful they will not fulfil all
programming needs because they apply only to widening conversions between
compatible types. For
All other cases you must employ a cast .a cast is an instruction to the compiler to
convert the outcome of an expression into a specified type. thus it request an
explicit type conversion.
A cast has this general form(target.type)expression
Here, target-type specifies the desired type to covert . he specified expression
too.for example given
doublex,y;
if you want type of the expression x/y to be int you can write int(x/y).
for example :-
using system;
classcastDemo
{
public static void Main(string []aegs)
{
double x, y;
byte b;
int I;
charch;
short s;
long l;
x=10.0;
y=3.0;
i=(int)(x/y);
Console.Writeline(“Integer outcome of x/y:”+i);
i=255;
b=(byte)I;
Console.Write(“b after assigning 255”+b+”no data lost”);
b=88;
ch=(char)b;
Console.Wrtieline(“ch after assigning 88:”+ch);
}
}
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#.
Operator Description
+ Adds two operands
- Subtracts second operand from the first
* Multiplies both operands
/ Divides numerator by de-numerator
% Modulus Operator and remainder of after an
integer division
++ Increment operator increases integer value by
one
-- Decrement operator decreases integer value by
one
Relational Operators
Following table shows all the relational operators supported by C#.
Operator Description
== Checks if the values of two operands are equal or not, if
yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if
Operator Description
&& Called Logical AND operator. If both the operands are
non zero then condition becomes true.
|| Called Logical OR Operator. If any of the two operands is
non zero then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical
state of its operand. If a condition is true then Logical
NOT operator will make false.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation.
Operator Description
& Binary AND Operator copies a bit to the result if it
exists in both operands.
| Binary OR Operator copies a bit if it exists in either
operand.
^ Binary XOR Operator copies the bit if it is set in one
operand but not both.
~ Binary Ones Complement Operator is unary and has
the effect of 'flipping' bits.
<< Binary Left Shift Operator. The left operands value is
moved left by the number of bits specified by the right
operand.
Assignment Operators
There are following assignment operators supported by C#:
Operator Description
= Simple assignment operator, Assigns values from right
side operands to left side operand
+= Add AND assignment operator, It adds right operand to
the left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to
left operand
*= Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to
left operand
/= Divide AND assignment operator, It divides left operand
with the right operand and assign the result to left
operand
%= Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left
operand
<<= Left shift AND assignment operator
>>= Right shift AND assignment operator
&= Bitwise AND assignment operator
^= bitwise exclusive OR and assignment operator
|= bitwise inclusive OR and assignment operator
Other Operators
There are few other important operators including sizeof, typeof and ? : supported by
C#.
Operator Description
sizeof() Returns the size of a data type.
typeof() Returns the type of a class.
& Returns the address of an variable.
* Pointer to a variable.
?: Conditional Expression
Is Determines whether an object is of a
certain type.
As Cast without raising an exception if the
cast fails.
}
Public static void Main (string [] args)
{
Program a=new program();
Int [] x={1,2,3,4,5};
a.print(x);
console.Readline();
}
}
significance of foreach loop:-
It does not use an integer index
It eliminates error caused by incorrect index handling.
It is use for read only purpose and do not have to specify exit.
1. value,
2. reference and
3. Output Parameters
Value Parameters:
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect
on the argument.
Reference Parameters:
This method copies the reference to the memory location of an argument into the
formal parameter. This means that changes made to the parameter affect the argument.
Output Parameters:
This method, meaning the method with output parameters, helps in returning more
than one value.
Call by value :
This is a parameter declared with no modifier is passed by value ans is called a value
parameter when a method is invoked .the values of actual parameter are assigned to
the corresponding formal parameter . the value of the value parameter can be change
within the method . the value of the actual parameter that is passed by value to a
method is not changed by any changes mode to the corresponding formal parameter
within the body of the method refer to only copies of those variables when they are call
by value.
For eg:-
Using system;
Class Increment
{
//define a function incr
public static void Incr(int i)
{
i++;
console.Writeline(i);
}
Public static void Main(string [] args)
{
Int x=2;
Incr(x);//calling a function incr
Console.Writeline(x);
}
}
Call by reference:
as ref the corresponding agreement in the method invocation must also be declared as
ref.
{
X+=10; //value of m will be changed.
}
………..
The use of ref int as the parameter type in the definition and use of ref keyword in the
method call to tell the compiler to call by reference rather than by value.
=>for eg:-
Using system;
Class Increment
{
//definition of function incr
Public static void Incr(ref int i)
{
i++;
Console.Writeline(i);
}
Public static void Main (string []args)
{
Int x=2;
Incr(ref x);//calling a fun incr
Console.Writeline(x);
}
}
Out parameter
They are used to pass result back to the calling method. This is achieved by declaring
the parameters with an out keyword. similar to a reference parameter does not create
a new storage location . Instead it because an alias to the parameter in the calling
{ x=100; }
Here, the actual parameter m is not assigned any values before it is passed as output
parameter since the parameter x and m refer to be the same storage location m takes
the value that is assigned to x.
=>for eg:-
Using system;
Class output
{
//define num1 function
Public static void Num1(int x, int y, out int z)
{
Console.Writeline(x+” “+y);
Z=x*y;
Console.Writeline(z);
}
Public static void Main(string [] args)
{
Int i=2; int j=3; int k;
Num1(I,j,out k) //calling num1 function
Console.Writeline(k);
}
}
In C# we can define methods that can handle variable number of argument using what
are known as parameter arrays. Parameter arrays are declared using the keyword
params.
{ }
Here, x has been declared as a parameter array. Note that parameter arrays must be
one-dimensional arrays. A parameter may be a part of a formal parameter list and in
such case it must be the last parameter .
ii)Using zero or more int type arguments for the parameter array.
eg: function(10,20);
the second invocation creates on it int type array with two elements 10 and 20 and
passes the newly created array as the actual argument to the method.
class params
{
//defining function parray
static void parray(params int[] arr)
{
console.writeline("Array elements are:");
foreach(int i in arr)
console.writeline(" "+i);
console.writeline();
}
public static void main()
{
int[] x={11,22,13};
Parray(x); //calling parray function
Parray( ); //calling parray function
Parray(100,200); //calling parray function
}
}
Example:
using System;
namespace myns{
class recurdemo{
static void PrintFibo(int a,int b,int n)//defining function with 4 params. n param to count
the number of elements in the series.
{
c=a+b; //adding first two parameters
if(c<n)
{
Console.Write(c+",");
//call printFibo fun again to print the series in the same manner
PrintFibo(b,c,n);//n should be reduced to n-1 as we printed an element
}
}
static void Main(){
int a,b,c,n;
a=0;
b=1;
Console.WriteLine("Enter the number of elements you want in series");
n=int.Parse(Console.ReadLine());
Console.Write(a+",");
Console.Write(b+",");
PrintFibo(a,b,n);
}
}}
Example 1
class Demo
{
private int age;
Public access modifier allows a class to expose its member variables and member
functions to other functions and objects. Meaning any public member can be accessed
from outside the class.
class Demo
{
public static void Main(string[] args)
{
Rect r = new Rect();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Area of Rect is: 15.75
In the preceding example, the member variables length and width are declared public,
so they can be accessed from the function Main() using an instance of the Rectangle
class, named r.
The member function Display() and GetArea() can also access these variables directly
without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed from
Main() using an instance of the Rectangle class, named r.
Private access modifier allows a class to hide its member variables and member
functions from other functions and objects. Only functions of the same class can access
its private members. Even an instance of a class cannot access its private members.
class Demo
{
public static void Main(string[] args)
{
Rect r = new Rect();
r.GetData(); //calling mutator
r.Display(); //calling public display function and thus calling CalcArea()
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Enter Length:
4.4
Enter Width:
3.3
Area of Rect is: 14.52
In the preceding example, the member variables length and width are declared private,
so they cannot be accessed from the function Main(). The member
functions GetData()and Display() can access these variables. Since the member
functions GetData() and Display() are declared public, they can be accessed
from Main() using an instance of the Rectangle class, named r.
Protected access modifier allows a child class to access the member variables and
member functions of its base class. This way it helps in implementing inheritance. The
example of the same will be explained in inheritance topic.
Internal access modifier allows a class to represent its member variables and member
functions to other functions and objects in the current assembly. It is similar to default
or friendly modifier of java. Java's friendly modifier members can be accessed from any
class or method defined within the package. Where as in C#, any member with internal
access modifier can be accessed from any class or method defined within the assembly
in which the member is defined.
For Example:
using System;
class Rect
{
//instance variables with friendly modifier
internal double length;
internal double width;
double CalcArea()
{
return length * width;
}
class Demo
{
public static void Main(string[] args)
{
Rect r = new Rect();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Area of Rect: 15.75
In the preceding example, notice that the member function CalcArea() is not declared
with any access modifier. Then the default access modifier of a class member is private.
The protected internal access modifier allows a class to hide its member variables and
member functions from other class objects and functions, except a child class within
the same application. Like of protected this modifier also will be implemented in
inheritance.
Null Constructor:
A constructor that initiates private properties of the class with null values by accepting
null parameter is termed as Null Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
//members are initialized with null values here.
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: ,
Default Constructor:
A constructor that initiates private properties of the class with their default values by
accepting null parameter is termed as Default Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
w=h=0; //members are initialized to their default values here.
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: 0,0
public Box()
{
w=5;
h=7;
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box();//construct an instance of Box b---process of instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: 5 , 7
Parameterized Constructor:
A constructor that initiates private properties of the class with dynamic values by
accepting parameters for the same is termed as Parameterized Constructor.
using System;
namespace consns
{
class Box
{
int w,h;
public Box(int w1,int h1)
{
w=w1; //w will be initialized to w1
h=h1; //h will be initialized to h1
}
public void display()
{
Console.WriteLine("The width and height of the Box is:"+w +" ," +h);
}
public static void Main(string []arg){
Box b=new Box(12,23);//construct an instance of Box b---process of
instantiation
b.display();
}
} }
When you run this program, you will get the following output:
The width and height of the Box is: 12 , 23
Static constructor:-
Static constructor is called before any object is created it is used to assign initial
value to static data members .
static constructor cannot have any parameter and it can have only static member
inside.
static variables are shared by all the object of a class & there is only one copy into
memory & we can change the value of static variable
constant variables are also shared by all objects, but no object can change its
value.
->For eg:
using System;
class Area
{
int x;
static int i;
constant int z=100;
static Area( )
{
i=00;
}
void print( )
{
console writeline(i);
}
public static void Main(string[]args)
{
Area a=new Area( );
a.print( );
}
}
When you run this program, you will get the following output:
0
using System;
class Area
{
int a,d;
float c;
Area(int i,int b)
{
a=i;
d=b;
}
void rectangle( )
{ int Rect=a*b;
console.writeline(Rect);
}
Area(int s)
{
a=s;
}
void Square( )
{
int squ=s*s;
console.writeline(squ);
}
Area(float rad)
{
c=rad;
}
void circle()
{
float circ=3.14*c*c;
Console.WriteLine(circ);
}
public static void Main(string[ ] agrs )
{
Area A1=new Area(2;5);
A1.Rectangle( );
Area A2= new Area(5);
A2.Square( );
Area A3=new Area(3.5f);
A.circle( );
}
}
1.7.10 Destructor:
using System;
namespace consns
{
class Box
{
int w,h;
public Box()
{
Console.WriteLine("Object is Created");
}
~Box()
{
Console.WriteLine("Object is Deleted");
}
public static void Main(string []arg){
Box b1=new Box();//calling constructor
Console.WriteLine("In Block1");
{
Box b2=new Box();//calling constructor
} //calling destructor
Console.WriteLine("In Block2");
{
Box b3=new Box();//calling constructor
} //calling destructor
} //calling destructor
}
}
When you run this program, you will get the following output:
Object is created
In Block1
Object is created
Object is deleted
In Block2
Object is created
Object is deleted
Object is deleted
Constant member
Static member
Read-only member
Constant member:
C# permits declaration of data fields of a class as constants this can be done using the
modifier constant.
The member size is assigned the value 100 at compile time and cannot be changed later.
Although constant members are implicitly static, we cannot declare them so explicitly
using static for eg. the statement public static constant int size=100; is wrong
and will produce compile time error;
ex:-
using System;
class Area
{const int z=100;
Area(int z)
{
z=x;
Console.WriteLine(z);
}
public static void Main(string[ ] args)
{
Area a=new Area(5);
}
}
Read-only members:
This is modifier is designed to set the value of the member using a constructor
method ,but cannot be modified later. The read-only members may be declared as
either static field are declared as instance fields, they can take different value with
different object.
=> ex:
using System;
class Area
{
readonly int y;
Area(int x)
{
y=x;
}
public static void Main(string[ ] agrs)
{
Area a= new Area(5);
Area a1= new Area(6);
Area a2= new Area(7);
}
}
Static members:
Assume that we want to define a number that is common to all the object and accessed
without a particular object that is the member belong to the class as a whole rather
than the object created from the class such members can be defined as follows:
static int x;
static int max(int a,int b);
The member that are declared static as shown above are called static members.
=>for ex:-
using System;
class Area
{
int x;
static int i;
static Area( )
{
i=100;
}
void print( )
{Console.WriteLine(i);
}
public static void Main(string[ ] agrs)
{
Area a=new Area( );
a.print( );
}
}
1.7.12 Inheritance
Rules of Inheritance:
a) The child class should inherit all the features of the parent class.
b) It should have its own unique features too.
c) The rule of substitutability should be followed. (Meaning, through sub/child class
object one can access all the features of parent class and child class as well.)
Output
I'm a Parent Class.
I'm a Child Class.
members of an existing class. This existing class is called the base class, and the new
class is referred to as the derived class.
For example, Whale IS-A mammal; Blue-whale IS-A Whale and hence Blue-whale IS-A
mammal and so on.
Mammal
Whale is Mammal
Whale
Blue Whale is
Mammal Blue Whale
Classical
Inheritance
When one class is derived from another Child class then this type of inheritance is called
multilevel inheritance. The diagram of the same will mimic like the one we have used to
explain classical inheritance. Blue whale---Whale---Mammal example.
Let us program the same example.
using System;
namespace inhns
{
class Mammal
{
protected void About(){
Console.WriteLine("The mammals include the largest animals on the planet, as
well as some of the most intelligent, some primates and some cetaceans");
}
}//mammal class is terminated
class Whale : Mammal
{
protected void Types()
{
About(); //calling base class about function to display about
mammals
Console.WriteLine("Whale is one of the largest mammals. There are
about 86 species of whales.");
}
}//whale class is terminated
}//namespace is terminated
1.7.12.3.1.3Hierarchical Inheritance:
B.Com
In the above diagram, even though B&I, A&F, FM courses are sibling courses, derived
from parent class B.Com, they can't share their properties and behaviours amongst
them. But they can inherit the features from its parent class of course as per the rule.
class HierInhDemo
{
public static void Main(){
BAF f=new BAF();
BFM m=new BFM();
BBI i=new BBI();
f.about();//will display about BAF course
m.about();//will display about BFM
i.about();//will display about BBI
//to display the features of BCOM course, any of the three objects can be
used.
i.features();
}
}
}
When you compile and execute the above program, the output will be
This course is the under-graduation course of commerce domain with the specialization
in accounts and finance
This course is the under-graduation course of commerce domain with the specialization
in financial markets
This course is the under-graduation course of commerce domain with the specialization
in banking and insurance
This course is the under-graduation course of commerce domain
Interface:
}
}
}
has-a has-a
Window
Door
class Window
{
int h,w;
public Window(int h,int w){
//when the parameter name and instance member's name is same, c# allows us to
use this keyword to differentiate the instance members and parameters.
this.h=h;
this.w=w;
}
public void getSize(){
Console.WriteLine("Dimension is:"+ h+" ," +w);
}
}
class Door
{
int n;
class Room{
public Window w;
public Door d;
public Room(){
w=new Window(300,200); //instantiated window object with the dimension
300X200
d=new Door(2); //instantiated Door object with number of doors in a room
}
}
class Demo{
public static void Main(){
Room myroom=new Room();
myroom.w.getSize();
myroom.d.getDoor();
}
}
When you compile and execute, the output will be:
Dimension is: 300,200
Number of Door is: 2
1.7.13
Polymorphism
Polymorphism means one name, many forms. One function behaves in different forms.
In other words, "Many forms of a single object is called Polymorphism."
Example 2
Your mobile phone, one name but many forms:
As phone
As camera
As mp3 player
As radio
Polymorphism can be
static or
dynamic.
In static polymorphism, the response to a function is determined at the compile time.
So it is otherwise termed as Compile-time polymorphism. As the function definition
statements are bound with their calling instructions at compile-time statically, it may
be termed as Early/Static binding.
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:
Function overloading
Operator overloading
Method/Function overloading:
In c# two or more method within the same class can share the same name as long as
their parameter declaration is different. Meaning we can have multiple definitions for
the same function name in the same scope. The definition of the function must differ
from each other by the types and/or the number of arguments in the argument list.
You cannot overload function declarations that differ only by return type.
When this is the case the method are said to be overloaded and the process is
referred to as method overloading.
For example:-
using System;
class Overload
{
public void ovlDemo()
{
Console.Writeline(“No Parameters”);
}
public void ovlDemo(int a)
{
Console.Writeline(“one Parameter:”+a);
}
public void ovlDemo(int a, int b)
{
Console.Writeline(“two Parameters:”+(a+b));
}
}
class OverloadDemo
{
public static void Main(string []args)
{
Overload ob=new overload();
Ob.ovlDemo();
Ob.ovlDemo(2);
Ob.ovlDemo(4,6);
}
}
When the above code is compiled and executed, it produces the following result:
No Parameters
One Parameter: 2
two Parameters: 10
Operator Overloading:
this.a=a;
this.b=b;
}
public void operator -(){//overloading negation operator
a=-a;
b=-b;
}
public void display(){
Console.WriteLine("A is:"+a);
Console.WriteLine("B is:"+b);
}
}
class UnaryOpDemo{
public static void Main(string arg[]){
Space s=new Space(6,-7.8);
Console.WriteLine("B4 Negation");
s.display();
-s; //s.-() is also an accepted instruction
Console.WriteLine("After Negation");
s.display();
}
}
When you compile the above given program, the output will be
B4 Negation
A is: 6
B is: -7.8
After Negation
A is: -6
B is: 7.8
C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class
inherits from it. Abstract classes contain abstract methods, which are implemented by
the derived class. The derived classes have more specialized functionality.
When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual functions. The virtual functions could be
implemented differently in different inherited class and the call to these functions will
be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
using System;
namespace PolymorphismApplication
{
abstract class Shape
{
70
Area: Area of a Square:
25
Method overriding is one of the types of inheritance and it is often identified as one of
the problems with inheritance. When super class and sub class have the same method
name with same signature, then sub class method overrides super class method upon
invocation through sub class object. Limiting the super class method in this passion is
otherwise termed as "Inheritance by limitation".
Object oriented languages such as C++ and Java supports this type of inheritance by
default. Meaning, they allow the sub classes to override their super classes by
redefining the methods of their parent classes.
But C# doesn't support this feature by default. The programmer can turn this feature
on by using the keywords
virtual---override key pair and
new
If they try those overriding, those instructions will be caught by C# compiler. So to try
out the method overriding, use the key pair virtual and override.
virtual---override keywords:
For example,
class ParentClass
{
}
If you compile the program the output will be
I will be displayed
If you want to experience the output of the parent class display(), then modify the
above program as given below.
using System;
namespace overridingns
{
class ParentClass
{
}
If you compile the program the output will be
I may be displayed
I will be displayed
New Keyword:
It is obvious that override keyword should be used only with virtual keyword. In case if
the parent class doesn't have any method with virtual keyword but if the sub class
wants to override the super class method, then the key pair will not work. In this
scenario, the new keyword will help us handy. Thus it helps method hiding feature in
C#. Meaning super class method is hidden by sub class using new keyword.
To implement the new keyword we modify the above program as given below.
using System;
namespace overridingns
{
class ParentClass
{
}
}
class ChildClass: ParentClass
{
public new void display(){
/* sub class may hide display() of super class */
Console.WriteLine(" I will be displayed");
}
}
class OverridingDemo
{
public static void Main(){
ChildClass c=new ChildClass();
c.display(); // it will invoke the sub class display().
}
}
}
If you compile the program the output will be
I may be displayed
I will be displayed
Sealed keyword in c# works like final keyword of java. This keyword can be used with
function and class. If it is used with function then its subclasses cannot override its
parent classes’ methods even with new and override keywords. If it is used with classes
then they cannot be overridden.
}
Class Myderived:SealedDemo
{
Public sealed override void checknum(int x)
{
Int y = x*x*x;
}
Public static void main(string[] args)
{
MyDerived A=newmyDerived();
A.checkNum(i);
}
}
Example of Sealed Keyword with class:-If we make a class as Sealed class then that class
cannot be inherited by any other class.
Example
Class sealed:-
Sealed class sealDemo
{
Int I;
}
// class My class; sealDemo
{
Public static void main(string[]a)
{
}
} error base class cannot inherit derived class since base is sealed.