UNIT -1
Introduction to .NET Framework:
In July 2000 Microsoft announced a whole new software development framework for Windows called .NET in the Professional Developer Conference (PDC). In March 2002 Microsoft released final version of the .NET framework. We can develop various varieties of applications in it. It provides complete SDK (Software Development Kit). In .NET SDK classes, interfaces and language compilers are included. The Microsoft .NET framework 2.0 includes 18619 types 12909 classes 401759 public method, 93105 public property 30546 public events. Now we are using .NET framework 4.0 and 4.5. If we are developing powerful applications then we may require some IDE (Integrated Development Environment) that allows us rapid action development. The new visual studio.NET provides such IDE. There is various versions of VS such as VS 2008, 2010, 2012, 2013 are available.
Terminology:To understand .NET framework properly we must have knowledge of some important terminologies.
· Common Language Runtime CLR: An important part of .NET framework is CLR (Common Language Runtime). CLR is responsible for executing our application code. It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation. Those codes which are directly managed by the CLR are called the managed code. · MSIL (Microsoft Intermediate Language): When we write an application for the .NET framework with any language our source code is compiled directly into machine code. Instead our code is converted into a special language name MSIL (Microsoft Intermediate Language). MSIL is a low level and platform independent language. In reality the .NET framework understands only one language MSIL. We can write application using any language such as VB.NET, C++, Ada, COBOL, Fortran, Pascal, PHP, Perl, Java script and many more. The .NET framework includes compiler for these language that enables us tocompile our code into MSIL. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific.· Framework Class Library: It contains a huge library of reusable types, classes, interfaces, structures and enumerated values, which are collectively called types. The .NET framework contains thousands of classes those we can use when building an application. The framework class library was designed to make it easier to perform most common programming tasks.
· Common Language Specification: It contains the specifications for the .Net supported languages and implementation of language integration.· Common Type System: It provides guidelines for declaring, using and managing types at runtime, and cross-language communication.· Namespaces: There are lots of classes in .NET framework. Microsoft divided the classes in framework into separate namespaces is simply a category to store the classes. Before we use a class in the program we must indicate the related namespace with the class name.· Assemblies: An assembly is the actual .DLL (Dynamic Linking Library) file on our hard disk, where the classes in the .NET framework arestored. In other words an assembly is the primary unit of deployment,security and version control in the .NET framework, because an assembly can span multiple files. An assembly is often referred to as alogical DLL.
· Metadata: is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory.C# (Sharp) and .NET: C# is a simple, modern, object oriented and type safe programming language derived from C and C++. C# language was developed by small
team of Microsoft engineer Anders Hejlsberg and Scott Wiltamuth.Hejlsberg is also known for creating Turbo Pascal.C# supports .NET framework and similar to java programming language. C# is a multi-paradigm programming language that encompasses functional, imperative, generic, object and component oriented programming disciplines. C# is one of the 44 programming languages supported by the .NET framework common language runtime. It was initially named cool which
stood for C like Object Oriented Language. However in July 2000 when Microsoft made the project public the name of programming language was given as C#.
Managed Execution Environment:
The comparison between (C# / IL Code / CLR) and (Java / Bytecode / JVM) is an inevitable and valid comparison to make. With C and C++ we generally compile the source code to assembly language which will run on a particular processor and a particular operating system. The compiler need to know which processor and operating system it is targeting, because processor may vary in instruction sets and operating system may vary in its functions. C and C++ model has been very successful but has its limitations.
· Program interface do not interact with other programs. Microsoft COM
(Component Object Model) was built to address this problem.
· Program can’t be used on different platforms.
Java addressed these problems by interpreting program to bytecode
which then runs on a virtual machine. This bytecode is machine
independent which means the same class file can be used on number of
platforms. But the interpretation is very slow process and it is never
appealing to the performance conscious programmer. Today most JVM
(Java Virtual Machine) use a Just In Time (JIT) compiler to make
compilation fast. The basic model .NET uses the same as described above.
The IL (MSIL) code has some improvements over byte code.
1. To provide greater type neutrality (helps implementation of templates).
2. To provide greater language neutrality.
3. To always be compiled to assembly language before executing and never
interpreted.
Similarities and Differences from Java:
C++ and Java have many similarities. We can discuss these similarities and
differences as follows:-
· Both have powerful reflection capabilities.
· C++ always uses .(dot) operator instead of arrow or scope resolution
operator.
· Null, Boolean / Bool keywords area available.
· Garbage collection coupled with the elimination of pointers.
· Compiles into machine independent codes. Java generates bytecode and
C# generate IL code.
· No header files, all code scoped to package or assemblies.
· No global function or constants everything belongs to a class.
· All values are initialized before use.
· Arrays and strings with length built-in and bounds checking.
· Both language support threads part of process such as open many tab in
a browser.
Structure of C# Program:
Before we study basic building blocks of the C# programming
language, let us look at a bare minimum C# program structure so that we
can take it as a reference in upcoming chapters.
A C# program basically consists of the following parts:
· Namespace declaration
· A class
· Class methods
· Class attributes
· A Main method
· Statements & Expressions
· Comments
Let us look at a simple code that would print the words "Hello World":
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:
Hello World
Let us look at various parts of the above program:
· The first line of the program using System; - the using keyword is used
to include the System namespace in the program. A program generally
has multiple using statements.
· The next line has the namespace declaration. A namespace is a
collection of classes. The HelloWorldApplication namespace contains
the class HelloWorld.
· The next line has a class declaration, the class HelloWorld contains the
data and method definitions that your program uses. Classes generally
would contain more than one method. Methods define the behavior of
the class. However, the HelloWorld class has only one method Main.
· The next line defines the Main method, which is the entry point for all
C# programs. The Main method states what the class will do when
executed.
· The next line /*...*/ will be ignored by the compiler and it has been put
to add additional comments in the program.
· The Main method specifies its behavior with the statement
Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System
namespace. This statement causes the message "Hello, World!" to be
displayed on the screen.
· The last line Console.ReadKey(); is for the VS.NET Users. This makes
the program wait for a key press and it prevents the screen from running
and closing quickly when the program is launched from Visual Studio
.NET.9610040036
It's worth to note the following points:
· C# is case sensitive.
· All statements and expression must end with a semicolon (;).
· The program execution starts at the Main method.
· Unlike Java, file name could be different from the class name.
Compile & Execute a C# Program:
If you are using Visual Studio.NET for compiling and executing C#
programs, take the following steps:
· Start Visual Studio.
· On the menu bar, choose File, New, Project.
· Choose Visual C# from templates, and then choose Windows.
· Choose Console Application.
· Specify a name for your project, and then choose the OK button.
· The new project appears in Solution Explorer.
· Write code in the Code Editor.
· Click the Run button or the F5 key to run the project. A Command
Prompt window appears that contains the line Hello World.
You can compile a C# program by using the command-line instead of the
Visual Studio IDE:
· Open a text editor and add the above-mentioned code.
· Save the file as helloworld.cs
· Open the command prompt tool and go to the directory where you
saved the file.
· Type csc helloworld.cs and press enter to compile your code.
· If there are no errors in your code, the command prompt will take you
to the next line and would generate helloworld.exe executable file.
· Next, type helloworld to execute your program.
· You will be able to see "Hello World" printed on the screen.
Language Features:
Type System: The common type system supports two general categories of
types, each of which is further divided into subcategories.
Value Types
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, float which stores numbers, alphabets,
floating point numbers, respectively. When you declare an int type, the
system allocates memory to store the value.
Reference Types
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 more than one variable, 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. Reference types can be self-describing types, pointer types, or
interface types.
Comman Type
System
Value Types
User Defined
Value Type
Enumeration
Built In Value
Type
Reference
Type
Self Deiscriptive
Type
Class Type
User Defined
Class
Boxed Value
Type
Delegates
Arrays
Pointer Type Interface type
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.
So 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.
When a value type is converted to object type, it is called boxing and
on the other hand, when an object type is converted to a value type, it is
called unboxing.
object obj;
obj = 100; // this is boxing
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.
Syntax for declaring a dynamic type is:
dynamic <variable_name> = value;
For example,
dynamic d = 20;
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 take place at run time.
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 = "Tutorials Point";
A @quoted string literal looks like:
@"Tutorials Point";
The user-defined reference types are: class, interface, or delegate. We will
discuss these types in later chapter.
Pointer Types
Pointer type variables store the memory address of another type.
Pointers in C# have the same capabilities as in C or C++.
Boxing and Unboxing:
Boxing and unboxing is an essential concept in .NET’s type system.
With Boxing and unboxing one can link between value-types and reference
(object) types by allowing any value of a value-type to be converted to and
from type object. Boxing and unboxing enables a unified view of the type
system wherein a value of any type can ultimately be treated as an object.
Converting a value type to reference(object) type is called Boxing.
Unboxing is the opposite operation and is an explicit operation.
.NET provides a unified type system. All types including value types
derive from the type object. It is possible to call object methods on any
value, even values of primitive types such as int.
The example
class Test
{
static void Main() {
int i = 1;
object ob = i; // boxing
int j = (int) ob; // unboxing
}
}
An int value can be converted to object and back again to int. This
example shows both boxing and unboxing. When a variable of a value type
needs to be converted to a reference type, an object box is allocated to hold
the value, and the value is copied into the box.
Unboxing is just the opposite. When an object box is cast back to its
original value type, the value is copied out of the box and into the
appropriate storage location.
Flow Controls:
Sometimes in programming we need to control flow of data and
control. For this purpose we use control flow statements. In C# there is
three types of control flow statements are available.
· Decision Making / Conditional Statement
· Iterative / Looping Statement
· Branching / Jumping Statement
C# provides following types of decision making statements.
Statement Description
if statement
An if statement consists of a boolean expression followed by one or
more statements.
if...else statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
nested if statements
You can use one if or else if statement inside another if or else if
statement(s).
switch statement
A switch statement allows a variable to be tested for equality against
a list of values.
Sometimes we need to repeat some task or calculations then we use looping
statements. C# provides following types of loop to handle repetition
requirements.
Loop Type Description
while loop
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.
for loop
Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
do...while loop
Like a while statement, except that it tests the condition at the end of
the loop body
Sometimes we need to stop a condition or loop in duration of processing.
Statement Type Description
break
It is used to stop the loop or condition. It transfers the control at
the end of that loop.
continue
It is also used to stop a loop or condition, But it transfers the
control at next iteration of the loop.
Objects and Classes
Object is an entity, place or person of our world that can be identified
according to their attributes and functions. For example boy, girl, pen,
register, Jaipur, Delhi, chair, table etc.
Class is group of similar things. In other words we can say that group
of similar objects is called a class. The attributes and functions of objects
are defined in a class. In programming context class is a user defined data
structure which combine data (variables) members and member functions
(methods). In C# class, we can use five types of access modifiers.
· private: the private data member or member function can be accessed
only inside of class.
· public: the public data member or member function can be accessed
outside of class.
· protected: the protected data member or member function can be
accessed only in its class or derived classes.
· internal : the internal data member or member function can be
accessed in an assembly or component that is being created but not to
the client of that component.
· protected internal: the protected or internal data member or member
function can be accessed in the containing program and assembly and
in the derived classes.
using System;
namespace BoxApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
public double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// Declare Box2 of type Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Constructor and Destructor
Constructor is a special member function of a class that is executed
whenever we create new objects of that class. A constructor will have exact
same name as the class and it does not have any return type. Following
example explains the concept of constructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
Console.WriteLine("Object is being created");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:
Object is being created
Length of line : 6
A destructor is a special member function of a class that is executed
whenever an object of its class goes out of scope. A destructor will have
exact same name as the class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters.
Destructor can be very useful for releasing resources before coming
out of the program like closing files, releasing memories etc. Destructors
cannot be inherited or overloaded.
Following example explains the concept of destructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line() // constructor
{
Console.WriteLine("Object is being created");
}
~Line() //destructor
{
Console.WriteLine("Object is being deleted");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}",
line.getLength());
}
}
}
When the above code is compiled and executed, it produces the following
result:
Object is being created
Length of line : 6
Object is being deleted
Inheritance:
One of the most important concepts in object-oriented programming
is that of inheritance. Inheritance allows us to define a class in terms of
another class, which makes it easier to create and maintain an application.
This also provides an opportunity to reuse the code functionality and fast
implementation time. When creating a class, instead of writing completely
new data members and member functions, the programmer can designate
that the new class should inherit the members of an existing class. This
existing class is called the base class, and the new class is referred to as the
derived class.Consider a base class Shape and its derived class Rectangle:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result: Total area: 35
Interface:
C# does not support multiple inheritance. However, we can use
interfaces to implement multiple inheritance. The following program
demonstrates this:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Base class PaintCost
public interface PaintCost
{
int getCost(int area);
}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
Total paint cost: $2450
Serialization in C#:
Conversion of an object into a data stream of bytes is known as
serialization for storage in database to various media. Serialization
performed by CLR (Common Language Runtime). In other words we can
say that serialization is an easy way to convert an object to a binary
representation that can be written to disk or sent over a wire. We can
serialize our own classes. We mark them with (Serializable) attribute. This
serializes all members of a class except those mark as (non-serialized).
.NET provides three serializers- binary, SOAP(Simple Object Access
Protocol), XML. To serialize an object we need to either mark the object
class with the (Serializable) Attribute or implement the ISerializable
interface. For example:-
The following is a class that is mark with the serializable attribute.
[Serializable]
Public Class Myclass
{
-----
----
}
If a class to serialized contains references to other objects. The classes of
those other objects must also be marked [Serializable] or implement the
ISerializable interface. We use interface if we want our class to control its
own serializable and deserialization. The ISerializable interface only has
one method.
GetDataObject( )
In this method we pass serialization info object and a streaming content
object. The GetDataObject( ) will populate the serialization info object with
the data necessary for the serialization of the target object.
Classes that implement this interface include System.Data.DataSet,
System.Drawing.Font, System.Collections.HashTable,
System.Drawing.Icon and System.Drawing.Image.
Delegates:
It is a powerful capability that C++ and some other languages have
addressed with function pointer. A delegate can be thought of as a type safe
object oriented function pointer, which is able to hold multiple methods
rather than just one. Delegates handle problems which would be solved with
function pointer in C++ and interface in Java. It improves on the function
pointer approach by mean type safe and being able to hold multiple
methods. It improves on the interface approach by allowing the invocation
of a method without the need for extra code to handle multiple method
invocation. The most important use of delegates is event handling. There are
three steps in defining and using delegates: Declaration, Instantiation and
invocation. Delegates can be declared as follows:-
delegates void simple ( );
C# provides a special rule for instantiation their instances. A delegate
creation expression is used to create new instance of a delegate. New
delegate data type (expression ) C# provides a special rule for invoking a
delegate.
delegate_object (parameter list)
Reflection:
Reflection is the ability to find out information about objects the
application details (assemblies). It is meta data at a runtime. In other words
reflection is the feature in .NET which enables us to get some information
about object in runtime. That information contains data of the class. It can
also get the name of methods that are inside the class and constructors of
that class. We can use reflection to dynamically create an instance of a type,
bind the type to an existing object or get the type from an existing object
and invokes its method or access its fields and properties. The system type
is the main class for reflection. System reflection name space contains all
the reflection related classes. These classes are used to get information from
any number of class under .NET framework. We should use system
reflection name space in our program. In which we are using reflection. In
C# we use reflection in following situations:
· When we need to access attributes in our program.
· For examining and instantiating types in an assembly.
· For building new types at runtime.
· For performing late binding, accessing, methods on types created at run
time.
No comments:
Post a Comment