Professional Documents
Culture Documents
http://www.academictutorials.com/c-sharp.net/
C# : C Sharp
C-Sharp
Introduction to .NET
Introduction:
Before we start explaining what .Net is? Lets discuss about Internet on business
organization. There are three phases of Internet.
First phase starts early in 1990’s, which brought big revolution. Organizations
created and launched their websites. The core idea behind this is to know “hit rate ”
means how many peoples are interested in their product and services. So that they can
update their products accordingly.
The 2nd is in which we are right now. Organization is generating revenues from on-
line trading.
We are moving into 3rd phase and here idea is to communicate peoples, partner
and share resources which are geographically far to run business successfully.
Here .net comes into picture, which is designed by Microsoft people, which provide to
build net based application which connect peoples and data at remote locations through
any devices (i.e. laptop, mobiles, and pda)
1
What is .net basically?
NET is the Microsoft Web services strategy to connect information, people, systems,
and devices through software. Integrated across the Microsoft platform, .NET
technology provides the ability to quickly build, deploy, manage, and use connected,
security-enhanced solutions with Web services. .NET-connected solutions enable
businesses to integrate their systems more rapidly and in a more agile manner and
help them realize the promise of information anytime, anywhere, on any device.
The Microsoft platform includes everything a business needs to develop and deploy a
Web service-connected IT architecture: servers to host Web services, development
tools to create them, applications to use them, and a worldwide network of more than
35k Microsoft Certified Partner organizations to provide any help we need.
.NET Framework
.NET is Microsoft’s new strategy for the development and deployment of software.
Depending on your interests and development background, we may already have a
number of preconceived notions regarding
NET fundamentally changes the way applications execute under the Windows Operating
System.
with .NET Microsoft is, in effect, abandoning its traditional Way of application
development, one which favors compiled components, and is embracing Interpreted
technology (similar, in many ways, to the Java Paradigm).
NET brings about significant changes to both C++ and Visual Basic, and introduces a
new language called C# .
NET is built from the ground up with the Internet in mind, embracing open Internet
standards such as XML and HTTP.
The .NET Framework can be distilled into the following three entities:
The Time-wasters will surround you all the sides and will tear away at your minutes
2
and hours, holding the back from producing a critical results which are vital to the
success in the career.
The Common Language Runtime (CLR)
CLR is execution environment for all programs in the .NET Framework. The CLR is
similar to a Java Virtual Machine (VM) in that it interprets byte code and executes it on
the fly, while simultaneously providing services such as garbage collection and
exception handling. Unlike a Java VM, which is limited to the Java language, the CLR is
accessible from any compiler that produces Microsoft Intermediate Language (IL) code,
which is similar to Java byte code. Code that executes inside the CLR is referred to as
managed code. Code that executes outside its boundaries is called unmanaged code.
. Net framework
It provides hundreds of prewritten services that user uses. These classes are the
building blocks for .NET applications. Every language had its own unique supporting
libraries, accessible only from that particular language. This library includes UI, Data,
Web, Diagonostic, and Ado.
System Requirements
System Requirements
In order to install the .NET Framework on your machine, Microsoft recommends the
following system configuration:
Processor: Minimum Pentium II-450Mhz (Pentium III-650Mhz recommended).
3
MB recommended) for Windows 2000 server.
Hard drive: 500MB free on the drive where the OS is installed (usually C:\) and 2.5
Gigs free on the installation drive (where VS.NET will be installed)..
Features of c: -
As a new programming language following features made this different from other
languages: -
Simple
Type safe
4
Versioning: making new version of an application from existing one to work.
Flexible
Versioning
Indexers
Boxing
Delegates
Application Types in C#
Application Types in C#
5
Empty Web Project Creates an empty project for creating a Web application.
Power of C++
Portability of Java
using System;
class Hello
{
static void Main ()
{
Console.WriteLine("hello, world");
}
}
The source code for a C# program is typically stored in one or more text files with a file
extension of .cs, as in hello.cs. Using the command-line compiler provided with Visual
Studio .NET, such a program can be compiled with the command-line directive
csc hello.cs , which produces an application, named hello.exe. The output produced by
this application when it is run is:
hello, world
The using System; directive references a namespace called System that is provided by
the Microsoft .NET Framework class library. This namespace contains the Console class
referred to in the Main method. Namespaces provide a hierarchical means of organizing
6
the elements of one or more programs. A "using" directive enables unqualified use of
the types that are members of the namespace. The "hello, world" program uses
Console. WriteLine as shorthand forSystem.Console.WriteLine.
The Main method is a member of the class Hello. It has the static modifier, and so it is
a method on the class Hello rather than on instances of this class. The entry point for
an application — the method that is called to begin execution — is always a static
method named Main. The "hello, world" output is produced using a class library. The
language does not itself provide a class library. Instead, it uses a class library that is
also used by Visual Basic .NET and Visual C++.NET.
The program does not use a global method for Main. Methods and variables are not
supported at the global level; such elements are always contained within type
declarations (e.g., class and struct declarations).
C# language does not use either "::" or "->" operators. The "::" is not an operator at
all, and the "->" operator is used in only a small fraction of programs — those that
employ unsafe code. The separator "." is used in compound names such as Console.
WriteLine.
The program does not contain forward declarations. Forward declarations are never
needed, as declaration order is not significant. C# does not use #include to import
program text. Dependencies among programs are handled symbolically rather than
textually. This approach eliminates barriers between applications written using multiple
languages..
.NET Type
TYPE:
C# supports two kinds of types: value types and reference types. Value types include
simple types (e.g., char, int, and float), enum types, and struct types. Reference types
include class types, interface types, delegate types, and array types.
Value types differ from reference types in that variables of the value types directly
contain their data, whereas variables of the reference types store references to objects.
With reference types, it is possible for two variables to reference the same object, and
thus possible for operations on one variable to affect the object referenced by the other
variable. With value types, the variables each have their own copy of the data, and it is
not possible for operations on one to affect the other. The example
7
class Test
{
static void Main ()
{
int val1 = 0;
int val2 = val1;
val2 = 123;
Class1 ref1 = new Class1();
Class1 ref2 = ref1;
ref2.Value = 123;
Console.WriteLine("Values: {0}, {1}", val1, val2);
Console.WriteLine("Refs: {0}, {1}", ref1.Value, ref2.Value);
}
}
The lines
The first argument is a string, which may contain numbered placeholders like {0} and
{1}. Each placeholder refers to a trailing argument with {0} referring to the second
argument, {1} referring to the third argument, and so on. Before the output is sent to
the console, each placeholder is replaced with the formatted value of its corresponding
argument
Developers can define new value types through enum and struct declarations, and can
define new reference types via class, interface, and delegate declarations.
8
The Law of an Excluded Alternative;
Object
The ultimate base type of all other types object o = null;
string
String type; a string is a sequence of Unicode characters string s = "hello";
9
short 16-bit signed integral type short val = 12;
Bool
The bool type is used to represent Boolean values: values that are either true or false.
The inclusion of bool makes it easier to write self-documenting code, and also helps
eliminate the all-too-common C++ coding error in which a developer mistakenly uses
"=" when "==" should have been used. In C#, the example
int i =…;
F (i);
if (i = 0) // the test should be (i == 0)
G();
Boolean type;
a bool value is either true or false
bool val1 = true;
10
bool val2 = false;
char
The char type is used to represent Unicode characters. A variable of type char
represents a single 16-bit Unicode character. Character type; a char value is a Unicode
character char val = 'h';
Decimal
The decimal type is appropriate for calculations in which rounding errors caused by
floating point representations are unacceptable. Common examples include financial
calculations such as tax computations and currency conversions. The decimal type
provides 28 significant digits.
Each of the predefined types is shorthand for a system-provided type. For example, the
keyword int refers to the struct System.Int32. As a matter of style, use of the keyword
is favored over use of the complete system type name.
Two expressions of type int are considered equal if they represent the same integer
value. Two expressions of type object are considered equal if both refer to the same
object, or if both are null. Two expressions of type string are considered equal if the
string instances have identical lengths and identical characters in each character
position, or if both are null.
11
Differences Between Values Types and Reference Types.
The following table shows some of the differences between values types and reference
types.
Int16
Int32
Double
12
(String is implemented as a class in .NET.)
If you are not very familiar with struct and class, don't worry about it. We can just use
them as if they are simple data types.
Here is how we can declare variables of type Int, Double and String:
Double salary;
sbyte System.SByte
byte System.Byte
char System.Char
13
float
System.Single
decimal System.Decimal
double System.Double
ushort System.UInt16
short System.Int16
uint System.UInt32
int System.Int32
ulong System.UInt64
long System.Int64
bool System.Boolean
string System.String
object System.Object
14
We will start with an introduction to what is object oriented programming, how to write
simple classes, creating objects etc.
What is a class’?
In modern object oriented programming, large computer programs are divided into
several 'classes'. Typically, a large project will have several hundred classes. A class
represents an entity in a program.
For example, if we are doing a small program called calculator, we will typically have a
single (or more) class called 'Calculator' .The class will have several ‘methods’ that will
do the functionality of the class
So, our calculator may have methods like the following:
Add ()
Subtract ()
Multiply ()
Divide ()
Here is a sample calculator class, written in C# :
using System;
15
return value1 / value2;
}
}
Methods
Any class in an object-oriented language has method and property members. These are
the places where the actual business logic or functionality is written and executed.
Method is object-oriented item of any language. All C# programs are constructed from
a number of classes and almost all the classes will contain methods. A class when
instantiated is called an object. Object-oriented concepts of programming say that the
data members of each object represent its state and methods represent the object
behavior.
Method Signature in C#: Each method is declared as follows:
For better understanding of methods let consider following example. We have a class
Man. It can have many fields like that:
The private members m_old and m_name define some state of objects that can be
16
created as instances of our class. Also the class Man has two methods, which serve
some of our requests. Method string WhatIsYourName() writes current object?s name
to the console and returns it, and the second one similar to first return age of man and
also writes an output to the console
The return type in the example above returns strings, which is an in-built data type.
The methods can also return any generic C# type or any custom types created by us.
Reference type
Strictly speaking there is no difference between ref and out parameters. The only
difference is that the ref input parameters need an input value and the out parameters
don?t.
17
Variable arguments in C#:
The C# language supports variable arguments through a keyword called params. A
typical example for the declaration of a function with variable argument signature is as
follows.
Property in C# class
Property in C# class
How do we access member variables of any class from outside the class? In most of
the languages including C++, we will make the member variables public so that we can
create an instance of the class and directly access the public fields, as shown below:
using System;
class Hello
{
static void Main () {
Console.WriteLine("hello, world");
}
}
The above class has one public field: color. We may access this field from outside the
class as shown below:
But this is the old way ! This would still work with C#, but the suggested approach is to
use "Property" instead of directly accessing member variables.
The following code snippet shows how to create "Property" in a class.
18
private string color;
// constructor
public Car()
{
}
The above class has one private field - color. Then we have one "Property" called
'Color', which is used to represent the private field. Note that the field is private and
the Property is public. (We have used the same name with upper/lower case to
represent the 'Property' and 'field', but we may give any name we want.)
Each property has two parts:
get
set
The get part is executed when we access the value of the Property as shown below:
When executed, the above get accessor will return the value stored in the field 'color'.
The set part is executed when we assign a value to the Property as shown below:
car.Color = "RED";
When executed, the above set accessor will assign the value "RED" to the private field
19
'color'. (Note that 'value' is a keyword, which will have the value assigned to it.)
// constructor
public Car()
{
}
20
thrown new Exception ("Wrong value.");
else
color = value;
}
}
}
Let us analyze the get part first. Here we are checking whether there is a valid value in
the field 'color' before we return the value. If it is empty, we are getting a chance to
return a default value 'Green'. This way, we can make sure that whoever calls the
property 'Color' will always get a valid color, never an empty string.
In the set part, we are doing a validation to make sure we always assign a a valid
value to our field. If someone assign an empty string to the 'Color' property, he will get
an exception (error).
car.Color = "";
The above code will throw an error because we are trying to assign an empty string
and the set accessor will throw an error if it an empty string. This way, we can make
sure that we allow only valid values to be assigned.
So, i guess now you would appreciate the purpose of "Property". So, no more public
fields! Always have private fields and write public properties as wrapper for them if
required to expose them to outside the class.
Arrays
Arrays
C# arrays are reference types. The size of the array is not part of the array type
int[] row;
int[,] grid;
Array instances are created using the new keyword. Array elements are default
initialised to zero (enums and numeric types), false (bool), or null (reference types).
21
int[] row = new int[4]{ 1, 2, 3, 4 }; // longhand
int[] row = { 1, 2, 3, 4 }; // shorthand
row = new int[4]{ 1, 2, 3, 4 }; // okay
row = { 1, 2, 3, 4 }; // compile time error
Array indexes start at zero and all array accesses are bounds checked
(IndexOutOfRangeException). All arrays implicitly inherit from the System.Array class.
This class brings array types into the CLR and provides some handy properties and
methods:
namespace System
{
public abstract class Array : .
.. {
...
public int Length { get { ... } }
public int Rank { get { ... } }
public int GetLength(int rank) { ... }
public virutal IEnumerator GetEnumerator() { ... }
...
}
}
Class Jagged
{
public static void Main()
{
int [][] jagged=new int [3][];
22
jagged[0]=mew int[4]
jagged[1]=mew int[3]
jagged[2]=mew int[5]
int I;
‘Storing values in first array
for (I=0;I<4;I++)
jagged[0][I]=I;
‘Storing values in second array
for( I=0;I<3;I++)
jagged[1][I]=I;
‘Storing values in third array
for(I=0;I<5;I++)
jagged[2][I]=I;
‘Displaying values from first array
for (I=0;I<4;I++)
Console.WriteLine(jagged[0][I])
‘Displaying values from second array
for (I=0;I<3;I++)
Console.WriteLine(jagged[1][I])
}
}
The element type of an array cans itself be an array creating a so-called “ragged”
array. Ragged arrays are not CLS compliant. We can use a foreach statement to iterate
through a ragged array or through a rectangular array of any rank:
class ArrayIteration
{
static void Main()
{
int[] row = { 1, 2, 3, 4 };
foreach (int number in row) {
...
}
int[,] grid = { { 1, 2 }, { 3, 4 } };
23
foreach (int number in grid) {
...
}
int[][] ragged =
{ new int[2]{1,2}, new int[4]{3,4,5,6} };
foreach (int[] array in ragged) {
foreach (int number in array) {
...
}
}
}
}
Method Overloading
Method Overloading
In complex applications written in C#, we may need many methods which do
essentially similar functions but are just different enough to be considered unique. For
example, we may have to calculate a person's tax liability and would need to
implement a method for doing this calculation in our application program. However,
there are many different rules when it comes to tax calculations and they vary
throughout the world. While there may be many rules, one basic equation stays the
same: Your net income equals your gross income minus a computed tax amount. We
would probably have to implement different methods for each type of tax calculation.
And, we could give each method a unique name such as TaxCalc1, TaxCalc2, TaxCalc3,
etc. But wouldn't it be nice to just name the method TaxCalc and pass different
arguments to it based on the computation desired?
Syntax:
How does C# know which method to call? It's easy. It knows which method to invoke
based on the number and type of arguments passed to it. This is also referred to as the
signature of the method. If C# sees you are calling TaxCalc with four arguments, then
it will call that method with four receiving arguments. The methods are all very similar
however they are differ by the number of arguments used in the tax calculation.
24
Caveat
It is important to remember that C# determines which method to call based upon the
method's signature. If you were to define two methods with the same name and the
same number and type of passed arguments, you would get a compile-time error .
However, we can have two methods with the same name and the same number of
arguments as long as the argument types differ.
Method overloading is a powerful concept in C# in that it helps to simplify code
reusability and clarity. If our example method of TaxCalc was placed in a .dll file
somewhere, we would only have to remember that I have to call TaxCalc and only fill in
the appropriate arguments to pass.
namespace OutNamespace
{
namespace WorkNamespace
{ /// can be placed some classes, structures etc.
25
}
}
Interfaces
Interfaces
An Interface is a reference type and it contains only abstract members. Interface's
members can be Events, Methods, Properties and Indexers. But the interface contains
only declaration for its members. Any implementation must be placed in class that
realizes them. The interface can't contain constants, data fields, constructors,
destructors and static members. All the member declarations inside interface are
implicitly public.
Defining an Interface:
Let us look at a simple example for c# interfaces. In this example interface declares
base functionality of node object.
interface INode
{
26
string Text
{
get;
set;
}
object Tag
{
get;
set;
}
int Height
{
get;
set;
}
int Width
{
get;
set;
}
float CalculateArea();
}
The above INode interface has declared a few abstract properties and function which
should be implemented by the derived classes.
27
set
{
m_text = value;
}
}
28
}
}
private int m_width = 0;
public float CalculateArea()
{
if((m_width<0)||(m_height<0))
return 0;
return m_height*m_width;
}
}
Now the above code has created a c# class Node that inherits from INode c# interface
and implement all its members. A very important point to be remembered about c#
interfaces is, if some interface is inherited, the program must implement all its declared
members. Otherwise the c# compiler throws an error.
The above code was a simple example of c# interface usage. Now this has to be
followed with some advanced details of interface building in C# .Net. The previous
example used only names of methods or properties that have the same names as in
interface. But there is another alternative method for writing the implementation for
the members in class. It uses full method or property name .
29
The above example created a class ClonableNode. It implements all the functionality of
INode interface in the same way as it was done in Node class. Also it realizes Clone
method only one item of IClonable interface of .NET library.
if(nodeC is INode)
Console.WriteLine("nodeC is object of INode type");
else
Console.WriteLine("nodeC isn't object of INode type");
In example nodeC object was created as ClonableNode type, but when we run program
"if operator" returns true. It means that nodeC also is of INode type.
Delegates in C#
Delegates in C# .Net:
If we look at C++ there is a feature called callback function. This feature uses Pointers
to Functions to pass them as parameters to other functions. Delegate is a similar
feature but it is more type safe, which stands as a stark contrast with C++ function
pointers. A delegate can hold reference/s to one more more functions and invoke them
as and when needed.
A delegate needs the method's name and its parameters (input and output variables)
when we create a delegate. But delegate is not a standalone construction. it's a class.
Any delegate is inherited from base delegate class of .NET class library when it is
declared. This can be from either of the two classes from System.Delegate or System.
MulticastDelegate.
If the delegate contains a return type of void, then it is automatically aliased to the
type of System.MulticastDelegate. This can support multiple functions with a +=
operator. If the delegate contains a non-void return type then it is aliased to System.
Delegate class and it cannot support multiple methods.
30
Let us have a look at the following sample code.
class Figure
{
public Figure(float a, float b, float c)
{
m_xPos = a;
m_yPos = b;
m_zPos = c;
}
public void InvertX()
{
m_xPos = - m_xPos;
}
public void InvertY()
{
m_yPos = - m_yPos;
}
public void InvertZ()
{
m_zPos = - m_zPos;
}
private float m_xPos = 0;
private float m_yPos = 0;
private float m_zPos = 0;
}
Now, we have a class named Figure and it has three private fields that use to store
position and three methods to invert this position by every axis. In main class we
declare delegate as follows:
In this example we create three delegates of FigureDelegate type and attach to these
31
elements our three methods from Figure class. Now every delegate keeps the address
of the attached function. The last line of code is very interesting, here we create a
delegate of base type (MulticastDelegate) and attach three of our already created
delegates. As all our methods are of void return type they are automatically of type
MutlticastDelegate and a MulticastDelegate can support multiple methods invocation
also. Hence we can write
Events in C# .Net
Events in C# .Net:
Delegate usefulness does not just lie in the fact that it can hold the references to
functions but in the fact that it can define and use function names at runtime and not
at compile time. A large goal of design delegates is their applicability in events model
of .Net. Events are the actions of the system on user manipulations (e.g. mouse clicks,
key press, timer etc.) or any event triggered by the program. To understand the usage
of delegates for event model, the previous examples are used here. We should add to
our Figure class next things:
Now we have a delegate declared and event that uses this delegate's type. In every
function we should call our event. The next code snippet should explain it clearly
32
private static void OnFigureInverted(string msg)
{
Console.WriteLine("Figure was {0}",msg);
}
So, in the main function we should create an object of figure class and attach event
handler to the method OnFigureInverted. And when we call any of invert methods the
event is fired and it calls our event handler. The application will print the following
string into the console: Figure was inverted by x-axis Figure was inverted by z-axis .
Reflection
Reflection
Reflection is one of the features of .Net framework and has greater importance during
the development of large applications. In brief it is a powerful way of collecting and
manipulate information present in application's assemblies and its metadata. Metadata
contain all the Type information used by the application. The ability to obtain
information at runtime also makes it even more advantageous. When reflection is used
along with system.type, it allows the developer to get the valuable information about
all the types and about the assemblies. We can even create the instances and then
invoke various types that are used across the application.
Reflection is the ability to find out information about objects, the application details
(assemblies), its metadata at run-time
This allows application to collect information about itself and also manipulate on itself.
It can be used effectively to find all the types in an assembly and/or dynamically
invoke methods in an assembly. This includes information about the type, properties,
methods and events of an object and to invoke the methods of object Invoke method
can be used too. With reflection we can dynamically create an instance of a type, bind
the type to an existing object, or get the type from an existing object and invoke its
methods or access its fields and properties. If Attributes (C#) are used in application,
then with help of reflection we can access these attributes. It can be even used to emit
Intermediate Language code dynamically so that the generated code can be executed
directly.
33
System.Reflection namespace contains all the Reflection related classes. These classes
are used to get information from any of the class under .NET framework. The Type
class is the root of all reflection operations. Type is an abstract base class that acts as
means to access metadata though the reflection classes. Using Type object, any
information related to methods, implementation details and manipulating information
can be obtained. The types include the constructors, methods, fields, properties, and
events of a class, along with this the module and the assembly in which these
information are present can be accessed and manipulated easily.
As mentioned earlier, we can use reflection to dynamically create an instance of any
type, bind the type to an existing object, or get the type from an existing object. Once
this is done appropriate method can be invoked, access the fields and properties. This
can be done by specifying the Type of object or by specifying both assembly and Type
of the object that needs to be created. By this the new object created acts like any
other object and associated methods, fields and properties can be easily accessed. With
reflection we can also find out about various methods associated with newly created
object and how to use these object. To find out the attributes and methods associated
with an object we can use the abstract class MemberInfo, this class is available under
the namespace System.Reflection.
Exception Handling
Exception Handling
Practically any program including c# .net can have some amount of errors. They can be
broadly classified as compile-time errors and runtime errors. Compile-time errors are
errors that can be found during compilation process of source code. Most of them are
syntax errors. Runtime errors happen when program is running.
It is very difficult to find and debug the run-time errors. These errors also called
exceptions. Rules of good coding style say that program must be able to handle any
runtime error. Exception generates an exception call at runtime. Exceptions in C# can
be called using two methods:
Using the throw operator. It call the manage code anyway and process an exception.
34
C# language uses many types of exceptions, which are defined in special classes. All of
them are inherited from base class named System.Exception. There are classes that
process many kinds of exceptions: out of memory exception, stack overflow exception,
null reference exception, index out of range exception, invalid cast exception,
arithmetic exception etc. This c# tutorial deals with DivideByZero c# exception and
custom classes in c# exceptions.
C# has defined some keywords for processing exceptions. The most important are try,
catch and finally.
The first one to be known is the try operator. This is used in a part of code, where
there exists a possibility of exception to be thrown. But operator ?try? is always used
with the operators: catch and finally.
See the following example of handling a simple exception in c#.
35
Some larger projects might have a requirement of creating their own custom exception
classes. Let us try to create class that validates email address. It will validate for the ?
@? symbol. Please have a look on the following piece of code:
Here were created a C# .Net TextException class that inherits from System.Exception
class of .NET class library. Actually it does nothing, but there is an additional class
MailValidator. It has TestEnteredMail method that raises a TextException. Now look at
usage of it in Main function.
try
{
MailValidator.TestEnteredMail(Console.ReadLine());
}
catch(TextException)
{
36
Console.WriteLine("Exception was passed");
}
So, if user enters mail address without “@” symbol throws an exception.
37