450 likes | 561 Views
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
E N D
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
Simple Program – console application // A first program in C#. using System; class Welcome1 { staticvoid 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
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)
i 123 s "Hello world" 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";
Programs • Write a C program to read three integer numbers and find their average.
Predefined TypesValue Types • All are predefined structs
Predefined TypesFloating Point Types • Follows IEEE 754 specification • Supports ± 0, ± Infinity, NaN
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
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
Predefined Typeschar • Represents a Unicode character • Literals • ‘A’ // Simple character • ‘\u0041’ // Unicode • ‘\x0041’ // Unsigned short hexadecimal • ‘\n’ // Escape sequence character
Predefined Typesstring • An immutable sequence of Unicode characters • Reference type • Special syntax for literals • string s = “I am a string”;
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();
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.
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)
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 @
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 way All C# keywords are lowercase!
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
C# • Keywords • Words that cannot be used as variable or class names • Have a specific unchangeable function within the language • Example: class
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 (@)
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
C# Statements • Anything in quotes (“) is considered a string • Every statement must end in a semicolon (;)
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.
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!”); } }
Welcome4.cs // Printing multiple lines in a dialog Box. using System; using System.Windows.Forms; class Welcome4 { staticvoidMain( string[] args ) { MessageBox.Show( "Welcome \n to \n C# \n programming!" );}}
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
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…
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); }
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.
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.
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.
Examples • Write a program to ask the user for the radius of a circle, and then display its area and circumference.