C++ Project
C++ Project
I am very thankful to the faculty of the institute Mr. Manjeet Singh to guide
my training and His support and continuous help at all times during my
summer training.
1
PREFACE
2
INTRODUCTION
W hy C# ?
As a technical leader (in MicrosoftTechnology) in Asia�s largest
consulting house Tata ConsultancyServices (TCS), I�ve been leading
various projects for various clientsover past two years. Publishing an
article was always in my mind (I�vewritten couple of articles on designing
COM components in Visual Basicand related problems), but never taken it
seriously. With variousarticles on .Net flashing in Microsoft site since
September 2000, I�vebeen closely following the development related to
.Net (Beta1 inJanuary and Beta2 in June�2001).�Currently Microsoft is
offering fourlanguages out of the box:
C#, VB.Net, Managed C++ and Jscript for application development on
.Netplatform and many more to come from various independent vendors.�
Sothe obvious question is which language is best suited for .Net?(Believe
me each time we meet for Technical Discussion, this has been afavorite
topic).
3
Managed C++
C++, even in its new managed form, definitelylags behind other languages
such as VB.NET and C# for their cleanersyntax and ease of use. So I
don�t expect any adition to the C++Developer community.�There's no
doubt, though, that experienced C++practitioners will continue to admire
and use its power, templates,multiple code inheritance and deterministic
finalisation.
C#
C# is the new language with the power of C++and the slickness of Visual
Basic.�It cleans up many of the syntacticpeculiarities of C++ without
diluting much of its flavour (therebyenabling C++ developers to transition
to it with little difficulty).�And its superiority over VB6 in facilitating
powerful OOimplementations is without question.C# with clean OO syntax
and large class library (in conjunction with.NET and the base class
libraries) could be the �most productivemainstream language� and it is
an ECMA-standard language that offersthe potential of being available
across many platforms.�For the serious developer wanting Microsoft's
most productive andmainstream .NET language, C# is the clear choice.
Features in C# 2.0
2. It aims to combine the high productivity of Visual Basic and the raw
power of C++.
4. Visual studio supports Vb, VC++, C++, Vbscript, Jscript. All of these
languages provide access to the Microsoft .NET platform.
4
7. CLR accommodates more than one languages such as C#, VB.NET,
Jscript, ASP.NET, C++.
9.The classes and data types are common to all of the .NET languages.
5
OVERVIEW OF C#
History of C#
Simple program of C#
Class sampleone
{
Public static void Main ()
{
System. Console. WriteLine(“C# is sharper than C++”);
}
}
6
LITERALS, VARIABLES AND
DATA TYPES
C# language provides for practically all the data types. These types can
be divided in three categories: value types, reference types and pointer
types.
There are some more basic concepts to be learnt before the discussion of
the data types. This is about variables and constants. A Variable is a
named cell of memory used for data storage. A Variable value can be
changed anytime. Every variable must have a type and this type must be
set before it is used. Qualifying a variable with a type is called as
declaration of variable. The type of a variable is the most important aspect
and it defines the behavior of variable. All variables can be divided into
seven main categories depending on the context of usage:
1. Static variables
2. Variable of instance
3. Array's elements
4. Parameters given by reference
5. Parameters given by value
6. Returned values
7. Local variables.
7
Common types in C#:
Object in C# language is universal; it means that all supported types are
derived from it. It contains only a couple of methods: Get Type() - returns a
type of object, To String() returns string equivalent of type that called.
Next type is class. It is declared in the same manner as structure type but it
has more advanced features.
Interface is an abstract type. It is used only for declaring type with some
abstract members. It means members without implementations. Please,
have a look at piece of code with a declaration for a simple interface:
interface IRect
{
int Width
{
get;
set;
}
int Height
{
get;
set;
}
int CalculateArea();
}
8
Literals
A literal is a source code representation of a value.
literal:
boolean-literal
integer-literal
real-literal
character-literal
string-literal
null-literal
Variables
Variables represent storage locations. Every variable has a type that
determines the values to be stored in the variable. C# is a type-safe
language and the C# compiler guarantees that values stored in variables
are always of the appropriate type. The value of a variable can be changed
through assignment or through use of the ++ and - operators.
Variables are values that can change as much as needed during the
execution of a program. One reason you need variables in a program is to
hold the results of a calculation. Hence, variables are locations in memory
in which values can be stored.
Variable Declarations
In C# all variables must be declared before they are used. In the declaration
you must specify a data type and a name for the variable so that memory
can be set aside for the variable. An optional initial value can be included
with the declaration if you know what the value should be to start.
9
Description
Value type variables are also known as stack variables because they are
stored on the stack. Value type variables can be directly declared and
referenced. As the variables go out of scope, they are removed from the
stack, ensuring the proper destruction of the variables. As the variables are
created on the stack, they are not initialised; that is the responsibility of the
program. The use of an uncapitalized variable will result in a compiler error.
Reference type variables are made up of two parts: the reference on the
stack and the object on the heap. The creation of the object and the
reference to the object is commonly known as the instantiation of the
object.
10
To declare a reference-type variable, the syntax used are:
11
C# OPERATORS
There are 8 types of Operators in C#
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
12
DECISION MAKING AND
BRANCHING
If Statements
if I lose ten pounds, I can get into my high-school bluejeans.
if (blnStockMarketCrashed){
BenBernanki.FreakOut();
}
if the temperature drops to minus ten degrees overnight, our water pipes
will burst.
if we get at least $2500 in our tax return, we'll pay off the car; otherwise,
we'll apply it toward our credit card debt.
if (condition){
// do this …
}
13
The switch statement
As you can see, if…else if…else can handle multiple choices. We could
have included several more else if above and the program would have
worked fine (assuming we didn't make a syntax error). But there is a better
way of handling multiple choices, and that is the switch statement, which
— like the if statement — is a way of controlling branching behavior in a
program. Personally, I prefer to use a switch statement anytime a simple
if…else won’t suffice. In other words, if we're not looking a simple either-or
case, but instead are dealing with multiple possibilities, it’s generally better
to use switch. The syntax of such a statement in C# looks like this:
switch(value){
case value1:
//code goes here
break;
case value2:
//code goes here
break;
.
.
.
case valueN:
//code goes here
break;
default:
//code goes here
break;
IF ELSE
14
TargetPractice();
}else{
15
while (test condition)
{
body of the loop
}
Here the given test condition is evaluated and if the condition is true then
the body of the loop is executed. After the execution of the body, the test
condition is once again evaluated and if it is true, the body is executed
once again. This process of repeated execution of the body continues
until the test condition finally becomes false and the control is transferred
out of the loop. On exit, the program continues with the statements
immediately after the body of the loop. The body of the loop may have one
or more statements. The braces are needed only if the body contained two
are more statements
Example program for generating ‘N’ Natural numbers using while loop:
16
the control enters the loop body and prints the value of I using the printf
statement and increments the value of I to the next natural number this
process repeats till the value of I becomes equal to or greater than the
number given by the user.
Do
{
statement;
}
while(expression);
17
void main() // start of your program
{
char inchar; // declaration of the character
do // start of the do loop
{
printf(“Input Y or N”); //message for the user
scanf(“%c”, &inchar); // read and store the character
}
while(inchar!=’y’ && inchar != ‘n’); //while loop ends
if(inchar==’y’) // checks whther entered character is y
printf(“you pressed u\n”); // message for the user
else
printf(“You pressed n\n”);
} //end of for loop
18
break; //if number –1 is input skip the loop
sum+=I; //else add the value of I to sum
num++ // increment num value by 1
}} end of the program
Continue statement:
During loop operations it may be necessary to skip a part of the body of
the loop under certain conditions. Like the break statement C supports
similar statement called continue statement. The continue statement
causes the loop to be continued with the next iteration after skipping any
statement in between. The continue with the next iteration the format of
the continue statement is simply:
Continue;
Consider the following program that finds the sum of five positive
integers. If a negative number is entered, the sum is not performed since
the remaining part of the loop is skipped using continue statement.
19
For Loop:
The for loop provides a more concise loop control structure. The general
form of the for loop is:
When the control enters for loop the variables used in for loop is
initialized with the starting value such as I=0,count=0. The value which
was initialized is then checked with the given test condition. The test
condition is a relational expression, such as I < 5 that checks whether the
given condition is satisfied or not if the given condition is satisfied the
control enters the body of the loop or else it will exit the loop. The body of
the loop is entered only if the test condition is satisfied and after the
completion of the execution of the loop the control is transferred back to
the increment part of the loop. The control variable is incremented using
an assignment statement such as I=I+1 or simply I++ and the new value of
the control variable is again tested to check whether it satisfies the loop
condition. If the value of the control variable satisfies then the body of the
loop is again executed. The process goes on till the control variable fails
to satisfy the condition.
20
Sets up two index variables I and j the former initialized to zero and the
latter to 100 before the loop begins. Each time after the body of the loop is
executed, the value of I will be incremented by 1 while the value of j is
decremented by 10.
Just as the need may arise to include more than one expression in a
particular field of the for statement, so too may the need arise to omit on
or more fields from the for statement. This can be done simply by omitting
the desired filed, but by marking its place with a semicolon. The
init_expression field can simply be “left blank” in such a case as long as
the semicolon is still included:
For(;j!=100;++j)
METHODS IN C#
Introduction to C#
Methods :
Just in the beginning I like to remind all of you that Computer programs
exist to solve a problems and there are methods for solving those problems.
21
blocks that solve a small problem.
For example you have a problem in your program. You need a method to
convert a string to integer array for some reason. You can use the
following method :
When you declare a variable in your method then it's a local variable to that
method and no other method can know anything about that variable.
Methods also very useful if you will use a block of code many times in your
program so instead of writing the same block of code many times in the
program we can put that code in a method and call it whenever we need it
to do the job.
Console.WriteLine(Math.Sqrt(9));
This line of code use the Sqrt method of the class Math to get the square
root of 9 . We need to create a method to write to the console screen the
22
square root just when we use it (when we call it, Invoke it). Let's take a look
at this method :
So this place where we will put the string into called a parameter. We just
tell the method "You have one place (a parameter) where can the user put a
value here (a parameter value) and you need this value to finish your task".
So when you create the method you specify the parameters that the
method will use and when you call it you will specify the parameters value
for the parameters. parameters value are the values that you specify for
your parameters when you call the function. Every parameters in your
method has a data type exactly like variables and you must specify it when
you create the method. When you call the method you must specify the
parameters value of the same data type or to a type that can be converted
to that type. The parameters of any method not accessible outside the
method because it's considered as local variables for that method.
23
We called the method SqrtToConsole with 9 as a parameter value for the
parameter x.
I think after you understand the concept of Parameters we can explain the
code written in the method SqrtToConsole.
The Math.Sqrt() method take also one parameter value to get its job done.
Here we just create our method and inside it we call the
Console.WriteLine() with a parameter value as the result of the following
method call Math.Sqrt(x).
Return Value :
Let's look at the Math.Sqrt() again please. This method takes a parameter of
double data type and Returns the square root of that parameter so this is
the return value that we are talking about here in C# methods.
24
}
Here the AddIntegers() method takes 2 integer numbers and return the
result as integer too.
The return value must have a type so here in our method the return value is
of type int and we must write int keyword before the method name to
specify the return type. Also we use the return keyword as the end of our
method to exit the method and return the value to the method which called
the AddIntegers() ( I will explain how we can call method from other method
later ) . So when you use the return keyword you tell the compiler to end
the method and return a value of the specified type to the calling code. If
your method does not return a value then you must use the void keyword
in the same place as you do with the return value type (before the method
name).
As you might know that the Main method is the entry point of any C#
program so it's the first method that the compiler will invoke. So any
method we created or any method we used it from FCL will be called from
the Main method. Consider the following example :
25
We need to call this methods from our Main method. All what we need to do
like that
We called the 2 methods simply by typing the name of the method with 2
empty parenthesis if the method's parameter list is empty or the with
parameters values inside the parenthesis if the method's parameter list
contains parameters.
STRUCTURES AND
ENUMURATIONS
Structures
Structures are basically value types. They are defined by using the struct
keyword. You can access the variables inside a structure by creating an
object of the structure. The only difference is that you don't have to use the
syntax for creating an object from a class for structures. Listing 1 explains
this concept clearly.
26
Listing 1
using System;
enum Employees:byte
{
ok = 50,cancel = 100
}
struct Emp
{
public Employees EM;
public string id;
}
class Emptest
{
public static void Main()
{
Emp E;
E.EM = Employees.cancel;
E.id = "002";
Console.WriteLine(E.EM);
Console.WriteLine(E.id);
}
}
Enumerations
27
Enumerations are a set of names for the corresponding numerical values.
Normally, we use them to apply the code
Listing 2
case 1:
Console.WriteLine("OK");
break;
case 2:
Console.WriteLine("CANCEL");
break;
Listing 3
enum Employees
{
OK; //
CANCEL;
}
Listing 4
28
enum Employees
{
OK = 50; //
CANCEL = 100;
}
Listing 5
Listing 6
using System;
enum Employees
{
Instructors,
Assistants,
Counsellors
}
class Employeesenum
{
public static void Display(Employees e)
29
{
switch(e)
{
case Employees.Instructors:
Console.WriteLine("You are an Instructor");
break;
case Employees.Assistants:
Console.WriteLine("You are one of the Assistants");
break;
case Employees.Counsellors:
Console.WriteLine("You are a counsellor");
break;
default:break;
}
30
CLASSES AND OBJECTS
Introduction to Objects and Classes in C# -
Prog rammer’s Classes and Objects
For example, we need to have persons objects in our program so the first
31
thing to do here is to create a class called Person that contains all the
functionalities or behaviors and properties of any person and after that we
will use that class (or template) to create as many objects as we need.
Creating an object of a specific class type is called "an instance of the
class". Don't worry if you didn't grasp it 100% and don't worry if you don't
know what the class and object's properties and functionalities or
behaviors are because we are still in the beginning. Until now I haven’t
provided any code examples. So let's take a brief of what is a class and
what is an object:
The class: A building block that contains the properties and functionalities
that describe some group of objects. We can create a class Person that
contains:
1. The properties of any normal person on the earth like: hair color,
age, height, weight, eye color.
2. The functionalities or behaviors of any normal person on the earth
like: drink water, eat, go to the work.
There are 2 kinds of classes: The built-it classes that come with the .NET
Framework , called Framework Class Library, and the programmer
defined-classes which we create ourselves.
The class contains data (in the form of variables and properties) and
behaviors (in the form of methods to process these data). We will
understand this concept later on in the article.
The object: It's an object of some classification (or class, or type) and when
you create the object you can specify the properties of that object. What I
mean here is: I, as an object, can have different properties (hair color, age,
height, weight) than you as another object. For example, I have brown eyes
and you have green eyes. When I create 2 objects I will specify a brown
color for my object's eye color property and I will specify a green color for
your object's eye color property.
32
OPERATOR OVERLOADING
Operator Overloading in C#
Description
We can have class Matrix which hold 2D array of elements.C# add doest
not Allows us to do Addition, Subtraction of matrices using the +,- operator
rather We use to write Methods AddMatrix(),SubMatrix() with the use of
Operator.
33
Overloading we make the user to code it:
Source Code:
34
//OverLoaded constructor with double argument
public Square(double s)
{
Console.WriteLine(".ctor with double argument");
Side=s;
}
//override ToString() method of object class.
public override string ToString()
{
Console.WriteLine("Override object class's string");
return this.Side.ToString();
}
//Overloading + operator to add 2 square objects and return new square
object
public static Square operator + (Square x,Square y)
{
Console.WriteLine("Overloading + with Square,Square");
return new Square(x.Side+y.Side);
}
//Overloading + operator to add square objects with double side and return
new square object
public static Square operator + (Square x,double y)
{
Console.WriteLine("Overloading + with Square,double");
return new Square(x.Side+y);
}
//Overloading + operator to add square objects with int side and return new
square object
//This is not necessary since C# automatically calls +(Square,double)
public static Square operator + (Square x,int y)
{
Console.WriteLine("Overloading + with Square,int");
return x +(double)y;
}
public static implicit operator Square(double s)
{
Console.WriteLine("Overloading = for Square s5=1.5 assignment");
return new Square(s);
}
public static implicit operator Square(int s)
{
Console.WriteLine("Overloading = for Square s5=10 assignment");
return new Square((double)s);
}
//OverLoading == operator
public static bool operator ==(Square x,Square y)
35
{
Console.WriteLine("Overloading == with Square,Square");
return x.Side==y.Side;
}
//OverLoading != operator
public static bool operator !=(Square x,Square y)
{
Console.WriteLine("Overloading != with Square,Square");
return !(x==y); //This will call to operator == simple way to implement !=
}
//Always override GetHashCode(),Equals when overloading ==
public override bool Equals(object o)
{
return this==(Square)o;
}
public override int GetHashCode()
{
return (int)Side;
}
//OverLoading > operator
public static bool operator >(Square x,Square y)
{
Console.WriteLine("Overloading > with Square,Square");
return x.Side>y.Side;
}
//OverLoading < operator
public static bool operator <(Square x,Square y)
{
Console.WriteLine("Overloading < with Square,Square");
return x.Side<y.Side;
}
//OverLoading <= operator
public static bool operator <=(Square x,Square y)
{
Console.WriteLine("Overloading <= with Square,Square");
return (x<y) || (x==y); //Calls to operator == and <
}
//OverLoading >= operator
public static bool operator >=(Square x,Square y)
{
Console.WriteLine("Overloading >= with Square,Square");
return (x>y) || (x==y); //Calls to operator == and >
}
//Readonly Property
public double Area
{
36
get
{
return 2*Side;
}
}
public static void Main()
{
Square s1=new Square(10);
Square s2=new Square(20);
Square s3=s1+s2; // This will call operator + (Square,Square)
Console.WriteLine(s3);
Console.WriteLine(s3+15); // This will call operator + (Square,int) and then
ToString()
Console.WriteLine(s3+1.5);// This will call operator + (Square,double) and
then ToString()
s3=10; // This will call operator Square(int)
Console.WriteLine(s3);
Square s4=10;
Console.WriteLine(s1==s4); //Calls == operator
Console.WriteLine(s1!=s4); //Calls != operator
Console.WriteLine(s1>s2); //Calls > operator
Console.WriteLine(s1<=s4); //Calls <= operator
}
}
// Source Code End
37
any clean up process.
try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
If any exception occurs inside the try block, the control transfers to the
appropriate catch block and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist
either with one or more catch blocks or a finally block or with both catch
and finally blocks.
If there is no exception occurred inside the try block, the control directly
transfers to finally block. We can say that the statements inside the finally
block is executed always. Note that it is an error to transfer control out of a
finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The
Exception is the ultimate base class for any exceptions in C#. The C# itself
provides couple of standard exceptions. Or even the user can create their
own exception classes, provided that this should inherit from either
Exception class or one of the standard derived classes of Exception class
like DivideByZeroExcpetion ot ArgumentException etc.
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing
program and exceptions generated by the common language runtime.
System.Exception is the base class for all exceptions in C#. Several
exception classes inherit from this class including ApplicationException
and SystemException. These two classes form the basis for most other
runtime exceptions. Other exceptions that derive directly from
System.Exception include IOException, WebException etc.
38
The common language runtime throws SystemException. The
ApplicationException is thrown by a user program rather than the runtime.
The SystemException includes the ExecutionEngineException,
StaclOverFlowException etc. It is not recommended that we catch
SystemExceptions nor is it good programming practice to throw
SystemExceptions in our applications.
• System.OutOfMemoryException
• System.NullReferenceException
• Syste.InvalidCastException
• Syste.ArrayTypeMismatchException
• System.IndexOutOfRangeException
• System.ArithmeticException
• System.DevideByZeroException
• System.OverFlowException
User-defined Exceptions
In C#, it is possible to create our own exception class. But Exception must
be the ultimate base class for all exceptions in C#. So the user-defined
exception classes must inherit from either Exception class or one of its
standard derived classes.
39
}
}
40
An interesting and useful property of a delegate is that it does not know or
care about the class of the object that it references. Any object will do; all
that matters is that the method's argument types and return type match the
delegate's. This makes delegates perfectly suited for "anonymous"
invocation.
Events
Events enable a class or object to notify other classes or objects when
something of interest occurs. The class that sends (or raises) the event is
called the publisher and the classes that receive (or handle) the event are
called subscribers.
Events Overview
41
• In the .NET Framework class library, events are based on the
EventHandler delegate and the EventArgs base class.
42