1 advanced programming c# introduction. application types console application has standard streams...
TRANSCRIPT
1
Advanced Programming
C#
Introduction
Application Types
Console Application Has standard streams (out, in, err) GUI can be added manually
Windows Application GUI based No standard streams (out, in, err) Main thread is shared by the GUI message pump & your
code
Service No standard streams (out, in, err) Main thread is commandeered by the SCM No GUI
Start Visual Studio
3
New Project
4
Windows Application
5
6
Simple Program – console application// A first program in C#.
using System;
class Welcome1
{
static void Main( string[] args )
{
Console.WriteLine( "Welcome to C# Programming!" );
} }
Constructions of Note
using like import in Java: bring in namespaces
namespace disambiguation of names like Internet hierarchical names and C++
naming class
like in C++ or Java single inheritance up to object
Constructions of Note
static void Main() Defines the entry point for an assembly. Four different overloads – taking string
arguments and returning int’s. Console.Write(Line)
Takes a formatted string: “Composite Format”
Indexed elements: e.g., {0} can be used multiple times only evaluated once
{index [,alignment][:formatting]}
Common Type System (CTS)
From MSDN
10
Atomic Data
11
Simple Program: Add Integers
Primitive data types Data types that are built into C#
string, int, double, char, long
Console.ReadLine() Used to get a value from the user input
Int32.Parse() Used to convert a string argument to an integer Allows math to be preformed once the string is
converted
Built-in Types C# predefined types
The “root” object Logical bool Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Floating-point float, double, decimal Textual char, string
Textual types use Unicode (16-bit characters)
Types Unified Type System
Value types Directly contain data Cannot be null
Reference types Contain references to objects May be null
int i = 123;string s = "Hello world;"
123i
s "Hello world"
14
Programs
Write a C program to read three integer numbers and find their average.
Predefined TypesValue Types
All are predefined structs
Signed sbyte, short, int, long
Unsigned byte, ushort, uint, ulong
Character char
Floating point float, double, decimal
Logical bool
Predefined TypesIntegral Types
C# Type System Type Size (bytes) Signed?
sbyte System.Sbyte 1 Yes
short System.Int16 2 Yes
int System.Int32 4 Yes
long System.Int64 8 Yes
byte System.Byte 1 No
ushort System.UInt16 2 No
uint System.UInt32 4 No
ulong System.UInt64 8 No
Predefined TypesFloating Point Types
Follows IEEE 754 specification Supports ± 0, ± Infinity, NaN
C# Type System Type Size (bytes)
float System.Single 4
double System.Double 8
Predefined Typesdecimal
128 bits Essentially a 96 bit value scaled by a
power of 10 Decimal values represented precisely Doesn’t support signed zeros, infinities
or NaN
C# Type System Type Size (bytes)
decimal System.Decimal 16
Predefined Typesbool
Represents logical values Literal values are true and false Cannot use 1 and 0 as boolean values
No standard conversion between other types and bool
C# Type System Type Size (bytes)
bool System.Boolean 1 (2 for arrays)
Predefined Typeschar
Represents a Unicode character Literals
‘A’ // Simple character ‘\u0041’ // Unicode ‘\x0041’ // Unsigned short
hexadecimal ‘\n’ // Escape sequence character
C# Type System Type Size (bytes)
Char System.Char 2
Predefined Typesstring
An immutable sequence of Unicode characters
Reference type Special syntax for literals
string s = “I am a string”;
C# Type System Type Size (bytes)
String System.String 20 minimum
Type System Value types
Primitives int i; Enums enum State { Off, On } Structs struct Point { int x, y; }
Reference types Classes class Foo: Bar, IFoo {...} Interfaces interface IFoo: IBar {...} Arrays string[] a = new string[10];
Delegates delegate void Empty();
23
ExampleAssume 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.
Program StructureMain Method
Execution begins at the static Main() method
Can have only one method with one of the following signatures in an assembly static void Main() static int Main() static void Main(string[] args) static int Main(string[] args)
25
C#
Comments
Comments can be created using //…
Multi-lines comments use /* … */
Comments are ignored by the compiler
Program StructureSyntax
Identifiers Names for types, methods, fields, etc. Must be whole word – no white space Unicode characters Begins with letter or underscore Case sensitive Must not clash with keyword
Unless prefixed with @
27
Identifiers: Keywords
Often we use special identifiers called keywords that already have a predefined meaning in the language Example: class
A keyword cannot be used in any other wayC# Keywords
abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach get goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void volatile while
All C# keywords are lowercase!
28
Arithmetic
Arithmetic operations
Asterisk (*) is multiplication
Slash (/) is division
Percent sign (%) is the modulus operator
Plus (+) and minus (-) are the same
There are no exponents
OperatorsAssociativity
Assignment and ternary conditional operators are right-associative Operations performed right to left x = y = z evaluates as x = (y = z)
All other binary operators are left-associative Operations performed left to right x + y + z evaluates as (x + y) + z
Use parentheses to control order
30
C#
Keywords
Words that cannot be used as variable or
class names
Have a specific unchangeable function
within the language
Example: class
31
C# Classes
Class names can only be one word long (i.e. no white space in class name )
Class names are capitalized, with each additional English word capitalized as well (e.g., MyFirstProgram )
Each class name is an identifier Can contain letters, digits, and underscores (_) Cannot start with digits Can start with the at symbol (@)
32
C# Class
Class bodies start with a left brace ({) Class bodies end with a right brace (})
Methods Building blocks of programs The Main method
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
33
C# Statements
Anything in quotes (“) is considered a string
Every statement must end in a semicolon (;)
34
C#
Escape sequence Description \n Newline. Position the screen cursor to the beginning of the
next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning
of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.
\\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote (") character. Some common escape sequences.
NameSpaces
You import namespaces when you want to be able to refer to classes by their short name, rather than full name
For example, import System.XML allows XmlDataDocument and XmlNode rather than System.XML.XmlDataDocument and System.XML.XmlNode to be in your code.
Program StructureNamespaces
namespace N1 { // N1 class C1 { // N1.C1 class C2 { // N1.C1.C2 } } namespace N2 { // N1.N2 class C2 { // N1.N2.C2 } } }
Program StructureNamespaces
The using statement lets you use types without typing the fully qualified name
Can always use a fully qualified name
using N1;
C1 a; // The N1. is implicitN1.C1 b; // Fully qualified name
C2 c; // Error! C2 is undefinedN1.N2.C2 d; // One of the C2 classesC1.C2 e; // The other one
Program StructureNamespaces
Best practice: Put all of your types in a unique namespace
Have a namespace for your company, project, product, etc.
Look at how the .NET Framework classes are organized
39
Namespaces Partition the name space to avoid name conflict! All .NET library code are organized using namespaces! By default, C# code is contained in the global
namespace To refer to code within a namespace, must use
qualified name (as in System.Console) or import explicitly (as in using System; )
using System;
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine(“Hello World!”);
}
}
class HelloWorld
{
static void Main(string[] args)
{
System.Console.WriteLine(“Hello World!”);
}
}
40
Welcome4.cs
// Printing multiple lines in a dialog Box.
using System;
using System.Windows.Forms;
class Welcome4
{
static void Main( string[] args )
{
MessageBox.Show( "Welcome \n to \n C# \n programming!" );} }
StatementsOverview
Statement lists Block statements Labeled statements Declarations
Constants Variables
Expression statements checked, unchecked lock using
Conditionals if switch
Loop Statements while do for foreach
Jump Statements break continue goto return throw
Exception handling try throw
StatementsExpression Statements
Statements must do work Assignment, method call, ++, --, new
static void Main() { int a, b = 2, c = 3; a = b + c; a++;Console.WriteLine(a + b + c); a == 2; // ERROR!}
Events
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
Interested parties use Event Handlers, which are a way of subscribing to the event
44
Math Class Methods The Math class
Allows the user to perform common math
calculations
Using methods
ClassName.MethodName( argument1, arument2, … )
Constants
Math.PI = 3.1415926535…
Math.E = 2.7182818285…
45
Math Class MethodsMethod Description Example Abs( x ) absolute value of x Abs( 23.7 ) is 23.7
Abs( 0 ) is 0 Abs( -23.7 ) is 23.7
Cos( x ) trigonometric cosine of x (x in radians)
Cos( 0.0 ) is 1.0
Exp( x ) exponential method ex Exp( 1.0 ) is approximately 2.7182818284590451 Exp( 2.0 ) is approximately 7.3890560989306504
Log( x ) natural logarithm of x (base e) Log( 2.7182818284590451 ) is approximately 1.0 Log( 7.3890560989306504 ) is approximately 2.0
Max( x, y ) larger value of x and y (also has versions for float, int and long values)
Max( 2.3, 12.7 ) is 12.7 Max( -2.3, -12.7 ) is -2.3
Min( x, y ) smaller value of x and y (also has versions for float, int and long values)
Min( 2.3, 12.7 ) is 2.3 Min( -2.3, -12.7 ) is -12.7
Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 Pow( 9.0, .5 ) is 3.0
Sin( x ) trigonometric sine of x (x in radians)
Sin( 0.0 ) is 0.0
Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 Sqrt( 9.0 ) is 3.0
Tan( x ) trigonometric tangent of x (x in radians)
Tan( 0.0 ) is 0.0
Example
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.
StatementsVariables and Constants
static void Main() { const float pi = 3.14f; const int r = 123; Console.WriteLine(pi * r * r);
int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c);}
48
Example
Write a program to ask you for the temperature in Fahrenheit and then convert it to Celsius. Given:C= 5/9 (F-32)
Write a program to ask you for the temperature in Celsius and then convert it to Fahrenheit.
49
Programs
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.
50
Examples
Write a program to ask the user for the width and length of a piece of land and then tell him how many orange trees he can grow on it. Given that each orange tree requires 4 m2.
51
Examples
Write a program to ask the user for the radius of a circle, and then display its area and circumference.