You are on page 1of 37

C# : C Sharp

http://www.academictutorials.com/c-sharp.net/

C# : C Sharp
C-Sharp

Before we start explaining what .Net is? Lets discuss about


Internet on business organization. There are three phases of
Internet.

.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.

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.

An Introduction To The .NET Framework

.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.

USER INTERFACE AND WINDOWS FORM

BASE CLASS LIBRARIES

COMMON LANGUAGE RUNTIME

. Net framework

The Base class libraries

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.

User interface and Win forms


This includes ASP.net pages or windows forms to interact with the application.

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).

Operating System: Windows 2000 (Server or Professional), Windows XP, or Windows


NT 4.0 Server.

Memory: 96 MB (128 MB recommended) for Windows 2000 Professional, 192MB (256

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)..

An introduction to C# (pronounced "C sharp")


C# (pronounced "C sharp") is a simple, modern, object-oriented, and type-safe
programming language. It will immediately be familiar to C and C++ programmers. C#
combines the high productivity of Rapid Application Development (RAD) languages.
Visual C# .NET is Microsoft's C# development tool. It includes an interactive
development environment, visual designers for building Windows and Web applications,
a compiler, and a debugger. Visual C# .NET is part of a suite of products, called Visual
Studio .NET, that also includes Visual Basic .NET, Visual C++ .NET, and the JScript
scripting language. All of these languages provide access to the Microsoft .NET
Framework, which includes a common execution engine and a rich class library. The
.NET Framework defines a "Common Language Specification" (CLS), a sort of lingua
franca that ensures seamless interoperability between CLS-compliant languages and
class libraries. For C# developers, this means that even though C# is a new language,
it has complete access to the same rich class libraries that are used by seasoned tools
such as Visual Basic .NET and Visual C++ .NET. C# itself does not include a class
library

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.

Follows all OOPs paradigm

Automatic garbage collection

Flexible

What c has added?


As compared to c++, following concepts are added into c: -
Assemblies

Versioning

Indexers

Boxing

Delegates

Application Types in C#

Application Types in C#

Creates a project for creating classes that can be used in


Class Library
other applications.
Creates a Visual C# application with a command-line
Console Application
interface.
ASP.NET Web Application Creates a Visual C# application with a Web user interface.
Creates an XML Web service with Visual C# that other
ASP.NET Web Service
applications can access.
ASP.NET Mobile Web Creates an application viewable on PDAs, cell phones, and
Application other mobile devices.
Empty Project Creates an empty project for creating a local application.

5
Empty Web Project Creates an empty project for creating a Web application.

To Begin With C# Programming

To Begin With C# Programming


C# is a language that provides
 Simplicity of Visual Basic

 Power of C++

 Concentrate on the high-value tasks;

 Portability of Java

First C# program to display “hello, world “ on the console

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

The example using System;


class Class1
{
public int Value = 0;
}

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 output produced is

Values: 0, 123 Refs: 123, 123

The lines

Console.WriteLine ("Values: {0}, {1}", val1, val2);


Console.WriteLine ("Refs: {0}, {1}", ref1. Value, ref2. Value);

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.

Eliminating the Time Wasters


The Time-wasters will surround you all the sides and will tear away at your minutes
and hours, holding the back from producing a critical results which are vital to the
success in the career.
 Eliminate a time wasters in life;

8
 The Law of an Excluded Alternative;

 Identify a major time-wasters;

 Practical ways to overcome and avoid them if possible.

Predefined Reference Types

Predefined Reference Types


The predefined reference types are object and string. The type object is the ultimate
base type of all other types. The type string is used to represent Unicode string values.
Values of type string are immutable.

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";

Predefined value types


The predefined value types include signed and unsigned integral types, floating-point
types, and the types bool, char, and decimal. The signed integral types are sbyte,
short, int, and long; the unsigned integral types are byte, ushort, uint, and ulong; and
the floating-point types are float and double.
 Eliminate a time wasters in life;

 The Law of an Excluded Alternative;

 Identify a major time-wasters;

 Practical ways to overcome and avoid them if possible.

sbyte 8-bit signed integral type sbyte val = 12;

9
short 16-bit signed integral type short val = 12;

int 32-bit signed integral type int val = 12;

long 64-bit signed integral type long val1 = 12;


long val2 = 34L;

byte 8-bit unsigned integral type byte val1 = 12;

ushort 16-bit unsigned integral type ushort val1 = 12;

uint 32-bit unsigned integral type uint val1 = 12;

float Single-precision floating point type float val = 1.23F;

double Double-precision floating point type double val1 = 1.23;

double val2 = 4.56D;

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();

results in a compile-time error because the expression i = 0 is of type int,


and if statements require an expression of type bool.

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.

Precise decimal type with 28 significant digits


decimal val = 1.23M;

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.

Value types Reference types


Allocated on stack Allocated on heap
A value type variable contains Reference type variable contains the address of
the data itself memory location where data is actually stored
When copying a reference type variable to another
When we copy a value type
variable, only the memory address is copied. Both
variable to another one, the
variables will still point to the same memory
actual data is copied and each
location, which means, if we change one variable,
variable can be independently
the value will be changed for the other variable
manipulated.
too.
integer, float, boolean, double
string and object are reference types.
etc are value types.
struct is value type. Classes and interfaces are reference types.

Data types in C# and .NET

Data types in C# and .NET


Data Types are the basic building block of any language. Microsoft has tried to
standardise the data types in .NET framework by introducing a limited, fixed set of
types that can be used to represent almost anything in programming world.
C++ was very rich in data types, but that leads to confusion too. Especially, when we
write components that may be consumed by applications written in other platforms, we
have to make sure the types used are compatible with other platforms too!
NET types start from a clean slate. All .NET languages share the same types. So, they
are all compatible and no worries. This means, we can call C# code from VB.NET and
vice versa, without worrying about type conversions.
NET data types are either structures or classes, part of the System namespace. For
example, the following data types are implemented as struct in .NET:

 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:

 Int16 age, employee Number;

 Double salary;

 String name, address;


we can use any of the .NET data types directly in any .NET language - in C#, VB.NET or
xyz. NET. But in addition to the .NET types, each language provides a set of primitive
types, which map to the corresponding types in .NET class library. This is why we may
see some people use string and some others use String. There is no big difference.
string is a primitive data type in C# and String is the corresponding class in .NET class
library. The string in C# is mapped to the class in .NET class library. So, whether we
use string or String, there is no real difference.

Data Types in C# and the corresponding class/struct in .NET class library


The following list shows the list of data types available in C# and their corresponding
class/struct in .NET class library.

C# Data type Mapped to .NET class/struct

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

Classes and Object Model in .NET

Classes and Object Model in .NET

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;

public class Calculator


{
public int Add(int value1, int value2)
{
return value1 + value2;
}

public int Subtract(int value1, int value2)


{
return value1 - value2;
}

public int Multiply(int value1, int value2)


{
return value1 * value2;
}

public int Divide(int value1, int value2)


{

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:

Return-type methodname ( Parameterslist );

For better understanding of methods let consider following example. We have a class
Man. It can have many fields like that:

public class Man


{
public Man(){}
private int m_old;
private string m_name;
public string WhatIsYourName()
{
Console.WriteLine(m_name);
return m_name;
}
public string HowOldAreYou()
{
Console.WriteLine(m_old.ToString());
return m_old;
}
}

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.

Passing Parameters to Methods in C#:


The input parameters can be passed in two ways.
 Value type

 Reference type

Output Parameters in Methods:


The return values in any function will be enough for any one if only one value is
needed. But in case a function is required to return more than one value, then output
parameters are the norm. This is not supported in C++ though it can be achieved by
using some programming tricks. In C# the output parameter is declared with the
keyword out before the data type. A typical example is as follows.

public void CalculateBirthYear(ref int year, out int birthyear)


{
int b = year - m_old;
Console.WriteLine("Birth year is {0}",b);
birthyear = b;
return;
}

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.

Public void functionName(int a, params int[] varParam);

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:

Car car = new Car ();

car. Color = "red";


string color = car.color;

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.

public class Car


{
// private fields.

18
private string color;

// constructor
public Car()
{
}

public string Color


{
get
{
return color; // return the value from privte field.
}
set
{
color = value; // save value into private field.
}
}
}

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:

Car car = new Car();

string color = car.Color;

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 car = new Car();

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.)

So, what is the difference ?


On the first look, there is no difference! We can achieve the same behaviour by writing
2 different methods ( like SetColor(...), GetColor() ).
First advantage of using property is, code looks cleaner than having 2 separate
methods. We can simply call a property as if it was a field in the class.
Well, then we may ask why make it 2 methods, we can make it a public field, so that
we can access it by creating an instance of the class.
The main advantage over using a Property instead of a public field is, with the
property, we will get a chance to write few lines of code (if we want) in the get and set
accessors. So, we can perform some validation or any other logic before returning any
values or assigning to the private field. See the modified class below:

public class Car


{
// private fields.
private string color;

// constructor
public Car()
{
}

public string Color


{
get
{
if ( color == "" )
return "GREEN";
else
return color;
}
set
{
if ( value == "" )

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 car = new Car();

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).

row = new int[42];


grid = new int[9,6];

Array instances can be initialised:

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() { ... }
...
}
}

What are Jagged Arrays in C#?


A special type of array is introduced in C#. A Jagged Array is an array of an array in
which the length of each array index can differ.
Example: A Jagged Array can be used is to create a table in which the lengths of the
rows are not same. This Array is declared using square brackets ( [ ] ) to indicate each
dimension.
The following code demonstrates the creation of a two-dimensional jagged array.

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])

‘Displaying values from third array


for(I=0;I<5;I++)
Console.WriteLine(jagged[2][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:

Public void functionName(int a, params int[] varParam);


Public void functionName(int a);

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.

Net C# Tutorial Namespaces

Net C# Tutorial Namespaces


A Namespace in Microsoft .Net is like containers of objects. They may contain unions,
classes, structures, interfaces, enumerators and delegates. Main goal of using
namespace in .Net is for creating a hierarchical organization of program. In this case a
developer does not need to worry about the naming conflicts of classes, functions,
variables etc., inside a project.
In Microsoft .Net, every program is created with a default namespace. This default
namespace is called as global namespace. But the program itself can declare any
number of namespaces, each of them with a unique name. The advantage is that every
namespace can contain any number of classes, functions, variables and also
namespaces etc., whose names are unique only inside the namespace. The members
with the same name can be created in some other namespace without any compiler
complaints from Microsoft .Net.
To declare namespace C# .Net has a reserved keyword namespace. If a new project is
created in Visual Studio .NET it automatically adds some global namespaces. These
namespaces can be different in different projects. But each of them should be placed
under the base namespace System. The names space must be added and used through
the using operator, if used in a different project.
using System;

namespace OutNamespace
{
namespace WorkNamespace
{ /// can be placed some classes, structures etc.

25
}
}

this example we create two namespaces. These namespaces have hierarchical


structure. We have some outer one named OutNamespace and the inner one called
WorkNamespace. The inner namespace is declared with a C# .Net class WorkItem.

Eliminating the Time Wasters


The Time-wasters will surround you all the sides and will tear away at your minutes
and hours, holding the back from producing a critical results which are vital to the
success in the career.
 Eliminate a time wasters in life;

 The Law of an Excluded Alternative;

 Identify a major time-wasters;

 Practical ways to overcome and avoid them if possible.

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.

Sample for Deriving a class using a C# .Net interface

public class Node : INode


{
public Node()
{}
public string Text
{
get
{
return m_text;
}

27
set
{
m_text = value;
}
}

private string m_text;


public object Tag
{
get
{
return m_tag;
}
set
{
m_tag = value;
}
}

private object m_tag = null;


public int Height
{
get
{
return m_height;
}
set
{
m_height = value;
}
}
private int m_height = 0;
public int Width
{
get
{
return m_width;
}
set
{
m_width = 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 .

Multiple Inheritance using C# interfaces:


Next feature that obviously needs to be explained is multiple inheritance using c#
interfaces. This can be done using child class that inherits from any number of c#
interfaces. The inheritance can also happen with a combination of a C# .Net class and
c# interfaces. Now let us see a small piece of code that demonstrate us multiple
inheritance using only interfaces as parent data types

class ClonableNode : INode,ICloneable


{
public object Clone()
{
return null;
}
// INode members
}

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.

is Operator for C# .Net interfaces -


At last a new C# operator that can be used to define that class should be explained. It
is the “ is “ operator. Look at the following piece of code:

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:

public delegate void FigureDelegate();

And now in the main function we should use it like this:

Figure figure = new Figure(10,20,30);


FigureDelegate fx = new FigureDelegate(figure.InvertX);
FigureDelegate fy = new FigureDelegate(figure.InvertY);
FigureDelegate fz = new FigureDelegate(figure.InvertZ);
MulticastDelegate f_del = fx+fy+fz;

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

Figure figure = new Figure(10,20,30);


FigureDelegate fMulti = new FigureDelegate(figure.InvertX);
fMulti += new FigureDelegate(figure.InvertY);
fMulti();

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:

public delegate void FigureHandler(string msg);


public static event FigureHandler Inverted;
public void InvertZ()
{
m_zPos = - m_zPos;
Inverted("inverted by z-axis");
}

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

static void Main(string[] args)


{
Figure figure = new Figure(10,20,30);
Figure.Inverted+=new Test.Figure.FigureHandler(OnFigureInverted);
figure.InvertX();
figure.InvertZ();
}

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.

How to use Reflection in our applications?

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.

If using the operators goes awry, it can generate an exception.

Different Types of Exceptions

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#.

// try catch exception


int zero = 0;
try
{
int div = 100/zero;
}
catch(DivideByZeroException)
{
Console.WriteLine("Division by zero exception passed");
}

This code in runtime throws a DivideByZeroException and writes some message


through the console. But if you want to release some resources that were created you
must use try ? finally construction. Finally will be called even if there were no
exceptions raised.

Bitmap bit = null;


// try finally exception
try
{
bit = new Bitmap(100,100);
}
finally
{
bit.Dispose();
Console.WriteLine("bitmap is disposed");
}

In the similar way we can use try ? catch ? finally construction.

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:

public class TextException : Exception


{
public TextException() : base()
{
}

public TextException(string message) : base(message)


{
}
}

public class MailValidator


{
MailValidator()
{
}

private static char symbol = '@';

public static void TestEnteredMail(string mailAddress)


{
if(mailAddress.IndexOf(symbol)==-1)
{
Console.WriteLine("The string entered is not a valid email address");
throw(new TextException());
}
}
}

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

You might also like