Advanced Programming C Introduction 1 Application Types n



















































- Slides: 51

Advanced Programming C# Introduction 1

Application Types n Console Application n n Has standard streams (out, in, err) GUI can be added manually n Windows Application n GUI based No standard streams (out, in, err) Main thread is shared by the GUI message pump & your code n Service n n No standard streams (out, in, err) Main thread is commandeered by the SCM

Start Visual Studio 3

New Project 4

Windows Application 5

Simple Program – console application // A first program in C#. using System; class Welcome 1 { static void Main( string[] args ) { Console. Write. Line( "Welcome to C# Programming!" ); }} 6

Constructions of Note n using n like import in Java: bring in namespaces n namespace n disambiguation of names n like Internet hierarchical names and C++ naming n class n like in C++ or Java n single inheritance up to object

Constructions of Note n static void Main() n Defines the entry point for an assembly. n Four different overloads – taking string arguments and returning int’s. n Console. Write(Line) n Takes a formatted string: “Composite Format” n Indexed elements: e. g. , {0} n n n can be used multiple times only evaluated once {index [, alignment][: formatting]}

Common Type System (CTS) From MSDN

Atomic Data 10

Simple Program: Add Integers n Primitive data types n Data types that are built into C# n string, int, double, char, long n Console. Read. Line() n Used to get a value from the user input n Int 32. Parse() Used to convert a string argument to an integer n Allows math to be preformed once the string is converted n 11

Built-in Types n C# predefined types n The “root” object n Logical bool n Signed sbyte, short, int, long n Unsigned byte, ushort, uint, ulong n Floating-point float, double, decimal n Textual char, string n Textual types use Unicode (16 -bit characters)

Types Unified Type System n Value types n Directly contain data n Cannot be null n Reference types n Contain references to objects n May be null int i = 123; string s = "Hello world"; i s 123 "Hello world"

Programs n Write a C program to read three integer numbers and find their average. 14

Predefined Types Value Types n All are predefined structs Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Character char Floating point Logical float, double, decimal bool

Predefined Types Integral Types C# Type System Type Size (bytes) Signed? sbyte System. Sbyte 1 Yes short System. Int 16 2 Yes int System. Int 32 4 Yes long System. Int 64 8 Yes byte System. Byte 1 No ushort System. UInt 16 2 No uint System. UInt 32 4 No ulong System. UInt 64 8 No

Predefined Types Floating Point Types n Follows IEEE 754 specification n Supports ± 0, ± Infinity, Na. N C# Type System Type Size (bytes) float System. Single 4 double System. Double 8

Predefined Types decimal n 128 bits n Essentially a 96 bit value scaled by a power of 10 n Decimal values represented precisely n Doesn’t support signed zeros, infinities or Na. N C# Type System Type Size (bytes) decimal System. Decimal 16

Predefined Types bool n Represents logical values n Literal values are true and false n Cannot use 1 and 0 as boolean values n No standard conversion between other types and bool C# Type System Type Size (bytes) bool System. Boolean 1 (2 for arrays)

Predefined Types char n Represents a Unicode character n Literals n ‘A’ // Simple character n ‘u 0041’ // Unicode n ‘x 0041’ // Unsigned short hexadecimal n ‘n’ // Escape sequence character C# Type System Type Size (bytes) Char System. Char 2

Predefined Types string n An immutable sequence of Unicode characters n Reference type n Special syntax for literals n string s = “I am a string”; C# Type System Type Size (bytes) String System. String 20 minimum

Type System n Value types n Primitives n Enums n Structs int i; enum State { Off, On } struct Point { int x, y; } n Reference types n Classes class Foo: Bar, IFoo {. . . } n Interfaces interface IFoo: IBar {. . . } n Arrays string[] a = new string[10]; n Delegates delegate void Empty();

Example Assume you work for the Alexandria Electricity company and you need a program to help you calculate the electricity bill for each customer. The program input should be the old meter reading and the new meter reading. Given that the price is 0. 10 pounds per kilowatt. 23

Program Structure Main Method n Execution begins at the static Main() method n Can have only one method with one of the following signatures in an assembly static n void Main() int Main() void Main(string[] args) int Main(string[] args)

C# n Comments can be created using //… n Multi-lines comments use /* … */ n Comments are ignored by the compiler 25

Program Structure Syntax n Identifiers n Names for types, methods, fields, etc. n Must be whole word – no white space n Unicode characters n Begins with letter or underscore n Case sensitive n Must not clash with keyword n Unless prefixed with @

Identifiers: Keywords r Often we use special identifiers called keywords that already have a predefined meaning in the language m Example: class r A keyword cannot be used in any other way All C# keywords are lowercase! 27

Arithmetic n Arithmetic operations n Asterisk (*) is multiplication n Slash (/) is division n Percent sign (%) is the modulus operator n Plus (+) and minus (-) are the same n There are no exponents 28

Operators Associativity n Assignment and ternary conditional operators are right-associative Operations performed right to left n x = y = z evaluates as x = (y = z) n n All other binary operators are left-associative n Operations performed left to right n x + y + z evaluates as (x + y) + z n Use parentheses to control order

C# n Keywords n Words that cannot be used as variable or class names n Have a specific unchangeable function within the language n Example: class 30

C# Classes n Class names can only be one word long (i. e. no white space in class name ) n Class names are capitalized, with each additional English word capitalized as well (e. g. , My. First. Program ) n Each class name is an identifier n Can contain letters, digits, and underscores (_) n Cannot start with digits n Can start with the at symbol (@) 31

C# Class bodies start with a left brace ({) n Class bodies end with a right brace (}) n n Methods n Building blocks of programs n The Main method n n n Each console or windows application must have exactly one All programs start by executing the Main method Braces are used to start ({) and end (}) a method 32

C# Statements n Anything in quotes (“) is considered a string n Every statement must end in a semicolon (; ) 33

C# 34

Name. Spaces n You import namespaces when you want to be able to refer to classes by their short name, rather than full name n For example, import System. XML allows Xml. Data. Document and Xml. Node rather than System. XML. Xml. Data. Document and System. XML. Xml. Node to be in your code.

Program Structure Namespaces namespace N 1 { class C 2 { } } namespace N 2 { class C 2 { } } } // N 1. C 1 // N 1. C 2 // N 1. N 2. C 2

Program Structure Namespaces n The using statement lets you use types without typing the fully qualified name n Can always use a fully qualified name using N 1; C 1 a; N 1. C 1 b; // The N 1. is implicit // Fully qualified name C 2 c; N 1. N 2. C 2 d; C 1. C 2 e; // Error! C 2 is undefined // One of the C 2 classes // The other one

Program Structure Namespaces n Best practice: Put all of your types in a unique namespace n Have a namespace for your company, project, product, etc. n Look at how the. NET Framework classes are organized

Namespaces r Partition the name space to avoid name conflict! r All. NET library code are organized using namespaces! r By default, C# code is contained in the global namespace r To refer to code within a namespace, must use in System. Console) or import explicitly (as in qualified name (as using System; ) using System; class Hello. World { static void Main(string[] args) { Console. Write. Line (“Hello World!”); } } class Hello. World { static void Main(string[] args) { System. Console. Write. Line (“Hello World!”); } } 39

// Printing multiple lines in a dialog Box. using System; using System. Windows. Forms; class Welcome 4 { static void Main( string[] args ) { Message. Box. Show( "Welcome n to n C# n programming!" ); } } 40

Statements Overview n n Statement lists Block statements Labeled statements Declarations n n Constants Variables n Expression statements n checked, unchecked n lock n using n Conditionals n if n switch w Loop Statements n n while do foreach w Jump Statements n n n break continue goto return throw w Exception handling n n try throw

Statements Expression Statements must do work n Assignment, method call, ++, --, new static void Main() { int a, b = 2, c = 3; a = b + c; a++; Console. Write. Line(a + b + c); a == 2; } // ERROR!

Events n Events are a way for an object to communicate with those that are interested in what it has to offer, like a button has a click event n Interested parties use Event Handlers, which are a way of subscribing to the event

Math Class Methods n The Math class n Allows the user to perform common math calculations n Using methods n Class. Name. Method. Name( argument 1, arument 2, … ) n Constants n Math. PI = 3. 1415926535… n Math. E = 2. 718285… 44

Math Class Methods 45

Example n A motor car uses 8 liters of fuel per 100 km on normal roads and 15% more fuel on rough roads. Write a program to print out the distance the car can travel on full tank of 40 liters of fuel on both normal and rough roads.

Statements Variables and Constants static void Main() { const float pi = 3. 14 f; const int r = 123; Console. Write. Line(pi * r); int a; int b = 2, c = 3; a = 1; Console. Write. Line(a + b + c); }

Example n Write a program to ask you for the temperature in Fahrenheit and then convert it to Celsius. Given: C= 5/9 (F-32) n Write a program to ask you for the temperature in Celsius and then convert it to Fahrenheit. 48

Programs n Write a program to ask a person for his height in feet and inches and then tell them his height in cms. Given that 1 foot = 30 cms and 1 inch = 2. 5 cms. 49

Examples n Write a program to ask the user for the width and length of a piece of land then tell him how many orange trees he can grow on it. Given that each orange tree requires 4 m 2. 50

Examples n Write a program to ask the user for the radius of a circle, and then display its area and circumference. 51