Division of Continuing Education
1 / 67

Catalog Description - PowerPoint PPT Presentation

  • Updated On :

Division of Continuing Education 31 College Drive Concord, New Hampshire 03301-7412 AG 120 Advance Topics in C++ and C# Department: EET/CPET/ BNCT/AGGP Hours per class: Lecture 2.0. Laboratory 2.0 Credits: 3 Course prerequisite: CP107

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Catalog Description' - Gideon

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Slide1 l.jpg

Division of Continuing Education31 College Drive Concord, New Hampshire 03301-7412

AG 120 Advance Topics in C++ and C#


Hours per class: Lecture 2.0. Laboratory 2.0Credits: 3Course prerequisite: CP107

Instructor: Professor Mohammad “Saleem” YusufPhone: Home (603) 424-8147 Work (781) 357-2635Email: [email protected], [email protected]

Class Dates and TimeWednesday nights, from 1/14/2009 to 4/29/2009 6:00 PM to 10:10 PM

 2007 Professor Yusuf, NHTI

Catalog description l.jpg
Catalog Description

Object Oriented Programming (OOP) and its effective design will be the major focus of this course. Encapsulation, inheritance and polymorphism are the key components of OOP to be emphasized. The language Microsoft .Net Framework C# will be introduced and reviewed to an intermediate level. Side by side comparisons of both C++ and C# will be part of this hands on course. The effective use of C++ pointers will be covered. The concepts of multithreaded programming will be explored using C#.

 2007 Professor Yusuf, NHTI

Slide3 l.jpg

Required Textbook

Visual C# 2008 How to Program, 3rd edition by Deitel.

Pearson / Prentice Hall. ISBN-13: 978-0-13-605322-4

Recommended but optional Textbook

The Complete Reference by Herbert Schildt. McGraw Hill / Osborne. ISBN 0-07-226209-5

 2007 Professor Yusuf, NHTI

Course objectives major focus is c l.jpg
Course Objectives- Major Focus is C#

  • Major Focus - C# Language, not C# 3.0 syntax

    • C# language syntax, types (reference and value), boxing, unboxing

    • Object Oriented Programming

    • Scope of objects, passing parameters, overloading methods and constructors, operator overloading.

    • Encapsulation, inheritance and polymorphism, abstract classes, interfaces

    • Differences between structs and classes and their usage

    • Exception Handling, including custom Exception Handling

    • Delegates and events

    • Threads and synchronization

    • Use of streams for files and to interact with networks and the web

    • Use of Debugging Tools

    • Graphics

    • User Interface Design (an introduction)

    • Introduction to XML, ADO .NET, ASP .NET and Web Services

 2007 Professor Yusuf, NHTI

Course objectives l.jpg
Course Objectives

  • C++ Main Topics

    • OOP In C++ (major focus)

    • Pointers (major focus)

    • Linked List with use of pointers (???)

    • Overloading (methods and operators)

    • Exception handling

    • Recursion (some coverage of the concept)

    • Templates (basic understanding)

    • STL (basic understanding)

    • UML (If time permits, some basic understanding)

 2007 Professor Yusuf, NHTI

Syllabus l.jpg

  • Location of all material

    • http://nhti.nhti.edu ask instructor for username & pwd

  • Is this course for you?

    • Goals & Outcomes

    • Course requirements

    • Reading & workload

    • Exams

    • Quizzes

    • In-class programming assignment

    • Programming assignments

    • Grades

 2007 Professor Yusuf, NHTI

Syllabus7 l.jpg

  • Read the following. It is in the syllabus document

    • School Policies

    • Late work

    • Absences

    • Academic honesty

    • Disruptive behavior

    • Disabilities

    • Class Cancellation

  • Class Schedule

    • Subject to change

 2007 Professor Yusuf, NHTI

Introduction to c programming language l.jpg
Introduction to C# Programming Language

  • C# (Pronounced C sharp)

    • Introduced by Microsoft in 2000 and it’s chief architect is Anders Hejlsberg. He called it a component-oriented language

    • It is an object-oriented programming language, very similar to Java and C++. For GUI development, very similar to VB

    • C# combines the high productivity of Rapid Application Development (RAD) languages and the raw power of C++

  • Visual C# .NET

    • Microsoft's C# development tool or IDE. Includes an interactive development environment, visual designers for building Windows and Web applications, a compiler, and a debugger.

    • Part of a suite of products, called Visual Studio .NET, that also includes Visual Basic .NET, Visual C++ .NET, and the JScript scripting language.

 2007 Professor Yusuf, NHTI

Introduction to c programming language9 l.jpg
Introduction to C# Programming Language

  • Component-Oriented language

    • C# is considered as a “Component-Oriented” language

  • What is a Component?

    • A binary unit of deployment

    • Usually composed of many objects and is language independent

    • Unlike an object which exists at run-time, components are binaries and are deployed

    • Combines with other components or assemblies to form an application

    • Implements one or more well-defined interfaces

    • Has properties, methods, events, attributes

 2007 Professor Yusuf, NHTI

Introduction to c programming language10 l.jpg
Introduction to C# Programming Language

  • Features worth mentioning

    • .NET environment

      • Ease of development and deployment

    • Garbage collection

      • Unlike C++, and like Java, makes it easy to write code

    • Exception Handling

      • C++ like exception handling

    • Versioning

      • Multiple version of assemblies with conflict

    • Type-safety

      • No un-initialized variables

 2007 Professor Yusuf, NHTI

Net platform l.jpg
.NET Platform

  • Microsoft .Net Platform

    • In July 2000 (official release V1.0 in 2002), Microsoft .NET Platform was launched

    • It is built on top of the operating system. It provides a programming platform for developers to build and deploy windows forms and web applications

    • Provides several core technologies and is a combination of the following

      • The .NET Framework

      • .NET My Services

      • The .NET Enterprises Servers

      • Visual Studio .NET

 2007 Professor Yusuf, NHTI

Net platform net framework l.jpg
.NET Platform.NET Framework

  • Microsoft .NET Framework

    • The .NET Framework consists of two main components

      • .NET FrameworkClass Library (FCL). A rich class library, common to all .NET Languages

        • This provides C# developers access to a complete set of class libraries that are used by other established languages such as Visual Basic .NET and Visual C++ .NET.

      • A common execution engine

        • Common Language Runtime (CLR).

        • Allows an application to use any .NET compliant language through the use of assemblies

    • It defines an environment that supports development and execution of distributed, component-based applications

    • It defines a "Common Language Specification" (CLS), a standard that ensures seamless interoperability between CLS-compliant languages and class libraries.

    • C# or any other language does not contain it’s class libraries specific to that language

 2007 Professor Yusuf, NHTI

Net platform net framework13 l.jpg
.NET Platform.NET Framework

  • The Two main parts of .NET Framework

  • Framework Class Library (FCS) or Base Class Library

    • Reusable code of library

    • All .NET languages use a common class library

      • Once familiar with a library , you can use it in all .NET language

  • Common Language Runtime (CLR)

    • Microsoft’s implementation of the CLI (Common Language Infrastructure, a standard approved by ECMA and ISO)

    • Handles code execution and all of the tasks associated with it (compilation, memory management, security, thread management, type enforcement and type use

 2007 Professor Yusuf, NHTI

Net platform net framework14 l.jpg


Windows Forms

Web Applications

ASP.NET, Web Services

Data Classes


Base Classes

System.IO, System.Drawing, System. Threading

Common Language Runtime (CLR)

CTS, Just-In-Time Compiler, Memory Management

.NET Platform.NET Framework

Core C# - Figure 1-1 .NET Framework

 2007 Professor Yusuf, NHTI

Objectives of net framework l.jpg
Objectives of .NET Framework

  • Provide a consistent, object-oriented development and runtime environment

  • Minimize version conflict “DLL Hell” and allow multiple versions of the same application to co-exists

  • Provide a portable environment, based on certified standards, that can be hosted by an operating system

  • “Managed Environment” in which code can be verified for safe execution

 2007 Professor Yusuf, NHTI

Common language infrastructure l.jpg
Common Language Infrastructure

  • Common Language Infrastructure

    • A standard that language developers must adhere to

    • CLI defines a platform independent virtual code execution environment that DOES NOT specifies an operating system. So the environment could be Linux or Windows

    • Microsoft’s implementation of CLI is CLR, the Common Language Runtime. CLR meets CLI requirements plus contains many more features

    • Many vendors have implemented languages that meets the CLI standard and are part of .NET

 2007 Professor Yusuf, NHTI

Cli standard environment l.jpg



Network Library



Runtime Infrastructure Library

Base Class Library

Kernel Profile

Compact Profile

CLI Standard Environment

Core C# Figure 1-2 Architecture defined by CLI specifications

 2007 Professor Yusuf, NHTI

Net framework clr l.jpg
.NET FrameworkCLR

  • Common Language Runtime

    • Common language runtime environment is also referred to as managed environment, in which common services such as garbage collection and security are automatically provided

    • Simplifies application development

    • Provides a secure and robust execution environment

    • Support multiple languages

    • Simplifies application deployment and management

 2007 Professor Yusuf, NHTI

Net framework fcl l.jpg
.NET FrameworkFCL

  • .NET Framework Class Library

    • A library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK

    • Provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built

    • Exposes features of the runtime and provides other services needed by developers

    • Available to all .NET Languages

    • The classes simplify development of .NET based applications

    • Developers can extend them by creating their own libraries of classes

 2007 Professor Yusuf, NHTI

Common language runtime l.jpg
Common Language Runtime

  • Communications between components

    • COM provided a way for components to integrate. However, each component had to provide the plumbing code

    • With the .NET Framework’s Common Language Runtime, objects can interact with each other without any plumbing code

      • No registration, GUIDs, .IDL files, HRESULTs, IUnknown, AddRef/Release, CoCreateInstance etc.

    • Classes and inheritance is supported across languages

    • COM classes can be imported as .NET classes

 2007 Professor Yusuf, NHTI

Clr cts cls l.jpg

  • The Common Language Runtime

    • CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.

  • Common Type System

    • Describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.

  • The Common Language Specification

    • An agreement among language designers and class library designers to use a common subset of basic language features (rules) that all languages have to follow.

 2007 Professor Yusuf, NHTI

Net language and other interoperability l.jpg
.NET Language and other Interoperability

  • .NET Languages share the same class library

  • .NET Programs can be in any .NET Language

    • Modules written in different languages can call each other and in the case of classes-inherit from each other

    • Debugging sessions in Visual Studio.NET crosses over language boundaries

    • Allows developers to choose the best language for each part of the application. All parts will work smoothly the other parts

    • Allows you to connect to unmanaged code, including COM libraries, ActiveX controls, and native (Win32) DLLs

    • A Win32 to .NET Framework API Map is available

  • Intermediate code from all .NET language is same

 2007 Professor Yusuf, NHTI

Slide23 l.jpg

Execution Support


Managed Environment






IL +Metadata

Base ClassLibraries


Common Language Runtime

Execution Engine

Class Loader

JIT Compiler




 2007 Professor Yusuf, NHTI

Compiled net code l.jpg
Compiled .NET Code

  • Compilers that are compliant with the CLR generate code that is targeted for the runtime as opposed to CPU (Intermediate Language, IL or MSIL)

  • IL code is assembler type code, packaged in a .EXE or .DLL, similar to byte-code from Java

  • IL code cannot run by itself. It requires JIT to convert it machine specific code

  • Framework + JIT takes IL code and puts out machine specific code

  • IL is portable across platform

  • Besides creating IL, compilers also put metadata in in every code module (more on metadata later)

 2007 Professor Yusuf, NHTI

What does clr manage l.jpg
What does CLR Manage?

  • Managed Code

    CLR executes intermediate code produced by .NET compliant compilers. It verifies code before executing and monitors and traps system exceptions

  • Managed Data

    CLR also allocates/de-allocates data on behalf of the developer. It automatically manages the heap and data segments

 2007 Professor Yusuf, NHTI

Un managed environment l.jpg
Un-Managed Environment

Source Code is typically one language, like VB or C++


Platform or Operating System

Compiler (Compile & Link)


The application runs by itself. If memory is not properly managed by the developer, application can hang or crash

 2007 Professor Yusuf, NHTI

Clr common language runtime l.jpg

Base Class Library Support

Thread Support

COM Marshaler

Type Checker

Exception Manager

Security Engine

Debug Engine

IL to Native






Class Loader

CLR – Common Language Runtime

 2007 Professor Yusuf, NHTI

Common language runtime execution model l.jpg


Common Language RuntimeExecution Model




Source code








Common Language Runtime JIT Compiler












CLR Services

Operating System Services

 2007 Professor Yusuf, NHTI

Common language runtime assemblies net binaries l.jpg
Common Language RuntimeAssemblies (.NET Binaries)

  • Assembly

    • All managed code that runs in .NET must be contained in an assembly

    • Logical unit of deployment. An .EXE or .DLL file

    • An assembly contains

      • Manifest

      • Metadata

      • MSIL

      • resources

    • Solution to the “DLL Hell” problem

      • DLL registration and existence of multiple version of DLLs

 2007 Professor Yusuf, NHTI

Assembly l.jpg










  • Figure 1-6 Multi-file assembly – Core C#

 2007 Professor Yusuf, NHTI

Net framework tools l.jpg
.NET Framework Tools

  • .NET Framework Tools

    • .NET Framework SDK tools are designed to make it easier for you to create, deploy, and manage applications and components that target the .NET Framework.

    • You can run most of the tools from the command line

      • Configuration and Deployment Tools

      • Debugging Tools

      • Security Tools

      • General Tools

    • Details can be found at (or search msdn for .NET Framework tools)

    • http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cptools/html/cpconNETFrameworkTools.asp

 2007 Professor Yusuf, NHTI

Application type l.jpg
Application Type

  • Console applications

    • Character based application. Usually no mouse support and no graphics, just characters

    • Primarily used for teaching programming languages

    • Common at one time. Almost died, but now, with .NET, many utility programs are console based

    • Uses Command prompt

  • Web Application

  • Windows applications

    • Windows or Forms

    • Contain Graphical User Interfaces (GUIs)

    • Like most current non-web applications

  • Assemblies

    • Programs that are used by other applications. Example .dll. Can also be .exe

 2007 Professor Yusuf, NHTI

Visual studio 2008 express edition l.jpg
Visual Studio 2008 (Express Edition)

  • An Integrated Development Environment (IDE)

  • Supports a many .NET languages and number will grow

    • C#, VB, C++, J#, Perl

  • Editor

  • Debugger – Can cross multiple languages

  • Build environment - Compiler and Linker

  • RAD Tool, to quickly build sophisticated GUI applications

 2007 Professor Yusuf, NHTI

Visual studio net 2005 l.jpg
Visual Studio .NET 2005

 2007 Professor Yusuf, NHTI

Creating a simple application l.jpg
Creating a Simple Application

  • Select File  New  Project  Console Application

  • From a link, select “New Project”. Then select Console Application as shown below. Enter a name for your application.

 2007 Professor Yusuf, NHTI

Saving your application l.jpg
Saving Your Application

 2007 Professor Yusuf, NHTI

Save the solution l.jpg
Save the Solution

 2007 Professor Yusuf, NHTI

Simple console application l.jpg
Simple Console Application

  • A Simple Console Application

//Author: Saleem Yusuf - A comment, ignored by compiler

using System;

namespace myFirstApp


class Program


public static void Main(string[] args)


Console.WriteLine("My FirstApp");




 2007 Professor Yusuf, NHTI

Details of the simple console application l.jpg
Details of the Simple Console Application

// Author: S Yusuf - A comment, ignored by compiler

using System;

namespace myFirstApp

  • Using Statement

    • Tells the compiler to search the system namespace when resolving reference. This eliminates the need for specifying fully qualified names.

    • System namespace contains all simple data types and is searched even if you do not include a “using System;” directive

  • Namespace

    • .NET class libraries are organized into namespaces

    • It is a name and a location given to types or your own code

    • It provides information to the compiler where to look for references

    • This also makes it possible to distinguish types with same name in different namespace

 2007 Professor Yusuf, NHTI

Details of the simple console application40 l.jpg
Details of the Simple Console Application


“myFirstApp” is the Name of the class you created

public static void Main(string[] args)

Function Main is the starting point of the program.

Keyword public is not needed. If there is no access specifier, default is public



public static void Main(string[] args)


Console.WriteLine("My FirstApp");



 2007 Professor Yusuf, NHTI

Details of the simple console application41 l.jpg
Details of the Simple Console Application

  • Function Main

    • Must be public

      • So that CLR can access it

    • Must be static

      • This is the starting point, so it should not have to instantiated before it can be used

      • Does not have to be void, can be anything. Typically an int or void

      • It can return a status to the program that called it

  • Namespace

    • .NET class libraries are organized into namespaces

    • It is a name and a location given to types or your own code

    • It provides information to the compiler where to look for references

    • This also makes it possible to distinguish types with same name in different namespace

 2007 Professor Yusuf, NHTI

Styles of comments supported in c l.jpg
Styles of Comments Supported in C#

  • Comments

    • C++ style

      • Preferred style. First introduced in C++, also used in Java

    • C style

  • XML document style - /// single line or /** text */ multi-line

//this line is a comment.

/* Old C type comment style

can span across multiple lines. Not recommended and is

prone to errors. */

/// <summary>

/// C# compiler can convert these comments into an XML file

/// Supported by Visual Studio .NET.

/// </summary>

 2007 Professor Yusuf, NHTI

Styles of comments supported in c43 l.jpg
Styles of Comments Supported in C#

  • XML comments

    • Begins with three slashes and usually contains XML tags that document a particular aspect of the code

    • C# compiler recognizes 9 primary tags that are associated with a particular program element

    • XML comments are exported to a XML file which can be processed for further use

    • By default, the compiler will not generate the XML file. You must explicitly tell the compiler to do this. Command line example:

c:\> csc myapp.cs /doc:myappAPI.xml

 2007 Professor Yusuf, NHTI

Xml tags advanced topic l.jpg
XML Tags (Advanced Topic)

 2007 Professor Yusuf, NHTI

C application l.jpg
C# Application

  • C# Application

    • Is a collections of one of more classes

    • A Class contains fields, properties and methods. It can also have nested classes and reference to other types

    • C# application can consist of many files and many classes. However, a class cannot span across multiple files (like in C++), unless you have partial classes

    • All applications have a starting point. Function Main is the starting point for a Console application

    • You can put a Main in every class. If you do, then you must specify which main function is the starting point of your application. Typically done for testing

    • Unlike Java, the file name does not have to be name of the (main) class

 2007 Professor Yusuf, NHTI

Reading and writing to console l.jpg
Reading and Writing to Console

  • Prompt user to enter a number and then display it back to the console

    • Read from console (string), then covert it to an int

    • Display it back to the screen using Console.Writeline

static void Main(string[] args)


int num; // declare variable to store data

Console.Write("Please enter a text message: ");

string input = Console.ReadLine();

Console.WriteLine("You entered: {0}", input);

Console.Write("Please enter a number: ");

// read string, then convert string to Int32

num = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("You entered: {0}", num);


 2007 Professor Yusuf, NHTI

Writing to console l.jpg
Writing to Console

  • Writing To Console

    • Both methods, Write and WriteLine are overloaded. They can take a number or string as argument.

Console.WriteLine(99);// Output a number

Console.WriteLine(“Ninety Nine“);// Output Text

Console.WriteLine(“Enter a number“);// has CR-LF

Console.Write(“Enter a number“);// No CR-LF

 2007 Professor Yusuf, NHTI

Reading and converting a string to an integer l.jpg
Reading and Converting a String to an Integer


  • Reads line of text (string) from the Console


  • Reads the next character from the Console


  • takes a string and converts to an integer (Int32)

  • Some other common methods of “Convert” class.

  • There are many conversion that can be performed (to and from)

  •  2007 Professor Yusuf, NHTI

    Identifiers l.jpg

    • Identifiers

      • A name given by the programmer to variables, functions, classes, interfaces (any user defined item)

      • Can contain a sequence of characters, digits, or underscores

      • Cannot start with a digit

      • Case sensitive

    decimal x = 50000.00M;

    int sum = 0;

    string s ="Saleem";

    _DispArgs (s);

    Identifiers are x, sum, s, _DispArgs

     2007 Professor Yusuf, NHTI

    Primitive or built in types l.jpg
    Primitive or Built in Types

     2007 Professor Yusuf, NHTI

    Types with examples suffix l.jpg
    Types with Examples, Suffix

     2007 Professor Yusuf, NHTI

    Types with examples suffix52 l.jpg
    Types with Examples, Suffix

     2007 Professor Yusuf, NHTI

    Primitive data type l.jpg
    Primitive Data Type

    • All types, user defied or primitive are derived from system’s object type

    • Tables in the preceding slides showed primitive types and their associated System type

    • Primitive types map directly to system types (base class library types) and can be used interchangeably

    • Shorter version (int) is an alias provided by C# for System.Int32. Like System.Int32 the underlying type for int is also a struct (will discuss shortly)

    System.Int32 age = new System.Int32(10);

    int age = 10;

    System.Int32 age = 17;// a shortcut

    int iMax = int.MaxValue;// returns largest int

    int pVal = int.Parse("100"); // converts str to int

     2007 Professor Yusuf, NHTI

    Numeric formatting l.jpg
    Numeric Formatting

     2007 Professor Yusuf, NHTI

    Examples of numeric formatting l.jpg
    Examples of Numeric Formatting

    decimal x = 50000.00M;

    double y = 500.00;

    Console.WriteLine("Currency: {0:C}, {1:c4}",x, y);

    Currency: $50,000.00, $500.0000

    Console.WriteLine("Integer: {0:D6}, {1:D}, {2}",25,35,45);

    Integer: 000025, 35, 45

    Console.WriteLine("Scientific: {0:E},{1:e2}", y, y);

    Scientific: 5.000000E+002,5.00e+002

    Console.WriteLine("General: {0:G},{1:g2}, {2:G6}", y, y, y);

    General: 500,5e+02, 500

    Console.WriteLine("Number: {0:N}, {1:n2}, {2:n6}", x, x, x);

    Number: 50,000.00, 50,000.00, 50,000.000000

    Console.WriteLine("Hex: {0:X4}, {1:X8}", 255, 255);

    Hex: 00FF, 000000FF

     2007 Professor Yusuf, NHTI

    Examples of numeric formatting56 l.jpg
    Examples of Numeric Formatting

     2007 Professor Yusuf, NHTI

    Text formatting l.jpg
    Text Formatting

    • Writing To Console

      • You can take a format string and additional parameters

      • Syntax is {N,M:FormatString}

        • N = Parameter number

        • M = Field width and Justification

      • Use \ as a escape character

    Console.WriteLine(“You entered {0}“, num1);//Formatting

    Console.WriteLine(“Sum: {0} + {1} = {2}“, x, y, (x+y));

    string s = "abc";

    Console.WriteLine("\"L Justified: {0, -10}\",{1}", 123, s);

    Console.WriteLine("\"R Justified: {0, 10}\", {1}", 123, s);

    Output, 123 is left and then right justified. Takes 10 chars

    "L Justified: 123 ", abc

    "R Justified: 123", abc

     2007 Professor Yusuf, NHTI

    Text formatting58 l.jpg
    Text Formatting

    • Writing To Console

      • Use @ char to display the entire string verbatim

      • Typically used for write path of a folder or file


     2007 Professor Yusuf, NHTI

    Implicit and explicit conversions l.jpg
    Implicit and Explicit Conversions

    • Up-casting, Implicit Conversion

      • Occurs automatically since there will be no data loss

      • From a smaller type to bigger type. No loss of precession

    • Down-casting, Explicit Conversion

      • Requires a cast. From bigger type to smaller type. Can result in loss of precession

    int n = 10;

    long m = n; //assigning int to long OK

    double x = n; //assigning long to Double OK

    double x = 3.333;

    float y = (float) x; //double may not fit in float

    int i = (int) x; //double may not fit in int

     2007 Professor Yusuf, NHTI

    Example similar to lab 1a l.jpg
    Example Similar to Lab – 1A

    • Write a simple console program

      • Declare a variable of type int, float, double, char and bool.

      • Initialize the variable (after declaring or when it is declared)

      • Print all the variables

      • Prompt the user to enter values for each type of the variable (one at a time or all at one time).

      • Read the values, overwriting the original values in the variable

      • Display all the values

     2007 Professor Yusuf, NHTI

    Slide61 l.jpg

    staticvoid Main(string[] args)


    int i;

    double x;

    char ch = 'a';

    i = 200;

    x = 55.978;

    System.Console.WriteLine("Integer {0}", i);

    System.Console.WriteLine("Double {0} and ch {1}", x, ch);

    //Prompt user to enter input, read int, double and char


    System.Console.Write("Enter an integer : ");

    i = Convert.ToInt32(System.Console.ReadLine());

    System.Console.Write("Enter a double : ");

    x = Convert.ToDouble(System.Console.ReadLine());

    System.Console.Write("Enter a character : ");

    ch = Convert.ToChar(System.Console.ReadLine());

    System.Console.WriteLine("Integer {0}", i);

    System.Console.WriteLine("Double {0} and ch {1}", x, ch);


     2007 Professor Yusuf, NHTI

    Strings l.jpg

    • A string of Unicode characters. It is an alias for String in the .NET Framework.

    • Strings are immutable -- the contents of a string object cannot be changed after the object is created

    • Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

    string a = "hello";

    string b = "h";

    //old b is destroyed and a new string b is created

    b += "ello";

    Console.WriteLine(a == b); //True

    Console.WriteLine((object)a == (object)b); //False

     2007 Professor Yusuf, NHTI

    Slide63 l.jpg

    • Char structure to represent Unicode characters

    • A String object is a sequential collection of Char structures that represents a string of text

    public static void Main()


    char chA ='A';

    char ch1 ='1';

    string str ="test string";

    Console.WriteLine(chA.CompareTo('B'));// Output: "-1" (meaning 'A' is 1 less than 'B')

    Console.WriteLine(chA.Equals('A'));// Output: "True"

    Console.WriteLine(Char.GetNumericValue(ch1));// Output:"1"

    Console.WriteLine(Char.IsControl('\t'));// Output: "True"

    Console.WriteLine(Char.IsDigit(ch1)); // Output: "True"

    Console.WriteLine(Char.IsLetter(','));// Output: "False"

     2007 Professor Yusuf, NHTI

    Slide64 l.jpg

    Console.WriteLine(Char.IsLetter(','));// Output: "False"

    Console.WriteLine(Char.IsLower('u'));// Output: "True"

    Console.WriteLine(Char.IsNumber(ch1));// Output: "True"


    Console.WriteLine(Char.IsSeparator(str, 4));// Output:"True"

    Console.WriteLine(Char.IsSymbol('+'));// Output: "True"

    Console.WriteLine(Char.IsWhiteSpace(str, 4));//Output:"True"

    Console.WriteLine(Char.Parse("S"));// Output: "S"

    Console.WriteLine(Char.ToLower('M'));// Output: "m"

    Console.WriteLine('x'.ToString());// Output: "x"


     2007 Professor Yusuf, NHTI

    Arithmetic binary operators l.jpg
    Arithmetic (Binary) Operators

    • Binary Operators

      • Statements of the form

        variable = variable operator expression;

        can also be rewritten as

        variable operator= expression;

        c = c + 3; This can be abbreviated as follows:

        c += 3; This is called a shortcut and is more efficient

    • Other arithmetic operators and shortcuts

      d -= 4; (d = d – 4;)

      e *= 5; (e = e * 5;)

      f /= 3; (f = f / 3;)

      g %= 9; (g = g % 9;)

    Assignment Operator

     2007 Professor Yusuf, NHTI

    Example lab1b arithmetic operators l.jpg
    Example Lab1B – Arithmetic operators

    class Program


    const double PI = 3.14159;

    static void Main(string[] args)


    int radius;

    double area, circumference;

    Console.Write("Enter radius of the circle : ");

    radius = Convert.ToInt32(Console.ReadLine());

    area = PI * radius * radius;

    circumference = 2 * PI * radius;

    Console.WriteLine("Area = {0},Circumference = {1}",

    area, circumference);



     2007 Professor Yusuf, NHTI

    References l.jpg

    Primary References

    • Visual C# 2005, How To Program, 2nd Edition, Deitel & Deitel, Prentice HallPrentice

    • Core C# and .NET by Stephen C. PerryC# Software Solutions by John Lewis

    • C# Language Specification – ECMA International. Standard ECMA-334, 3rd Edition / June 2005

    • MSDN

    • http://www.publicjoe.f9.co.uk/csharp/tut/csharp01b.html

      Other references

    • Slides from Microsoft’s website, that includedAnders Hejlsberg, (OOPSLA 2002), and others.

    • Slides from internet (Mark Sapossnek, Boston University)

    • You Can Do It!http://www.spellen.org/youcandoit/glossary.ht

     2007 Professor Yusuf, NHTI