2ac4ad9589f09e0eabc4864337015d42.ppt
- Количество слайдов: 59
Introduction to Programming in C# John Galletly
The Basics
What is "C#"? • “Flagship” language for Microsoft’s. NET Framework • C# features: – New cutting edge language – Extremely powerful – Easy to learn – Easy to read and understand – Object-oriented
Why C#? • Can be used to develop a number of different types of applications – Software components – Mobile applications – Dynamic Web pages – Database access components – Windows desktop applications – Web services – Console-based applications
Syntax – Writing C# Programs In a lot of areas, C# and Java are syntactically similar to each other, and also similar to C and C++. However, there are differences between C# and the other languages - Some of which are infuriating!
Object-Oriented Programming • Construct complex systems that model real-world entities • Facilitates designing components • Assumption is that the world contains a number of entities that can be identified and described by software objects
Microsoft’s. NET Framework • Not an operating system • An environment in which programs run • Resides at a layer between operating system and other applications • Offers multilanguage independence – One application can be written in more than one language • Includes over 2, 500 reusable types (classes) • Enables creation of dynamic Web pages and Web services • Scalable component development
What is. NET Framework? • Environment for execution of Micrsoft. NET programs • Powerful library of classes • Programming model • Common execution engine for many programming languages – C# – Visual Basic. NET –. . . and many others
Inside. NET Framework
Console Applications • Normally send requests to the operating system • Display text on the command console • Easiest to create – Simplest approach to learning software development – Minimal overhead for input and output of data
Windows Applications • Applications designed for the desktop • Designed for a single platform • Use classes from System. Windows. Form • Applications can include menus, pictures, drop-down controls, buttons, text boxes, and labels • Use drag-and-drop feature of Visual Studio
Web Applications • C# was designed with the Internet applications in mind • Can quickly build applications that run on the Web with C# – Using Web Forms: part of ASP. NET
Visual Studio. NET (VS. NET) • A single IDE for all forms of. NET development – From class libraries to form-based apps to web services – And using C#, VB, C++, J#, etc.
C# Introduction
Class The class is the basic unit in C#. Every executable C# statement must be placed inside a class. Every C# program must have at least one class, and one method called Main() in that class. A class is just a template or blueprint for defining objects.
Basic syntax for class declaration Class comprises a class header and class body. class_name { class body } Note: No semicolon (; ) to terminate class block. But statements must be terminated with a semicolon ; Class body comprises class members – constructor, data fields and methods.
The Method Main • Every C# application must have a method named Main() defined in one of its classes. – It does not matter which class contains the method - you can have as many classes as you want in a given application - as long as one class has a method named Main. • The Main method must be defined as static. – The static keyword tells the compiler that the Main method is a global method, and that the class does not need to be instantiated for the method to be called. - May also include the access modifier public
Syntax for simple C# program Programmer-defined class name // Program start class_name { // Main begins program execution public static void Main(string[] args) { statements May be replaced } by Main() } A C# program starts with a class which encapsulates the method Main() Note: Main() – not main()
Simple C# program // Program start class Hello. World { // Main begins program execution static void Main() { System. Console. Write. Line("Hello World"); } }
Include the standard namespace "System" using System; Define a class called "Hello. World" Define the Main() method – the program entry point class Hello. World { static void Main() { Console. Write. Line("Hello World!"); } } Write text message on the screen by calling the method "Write. Line" of the class "Console"
To access classes and methods without using their fully qualified name, use the using directive. Example using System; Instead of writing System. Console. Write. Line() May write using System; Console. Write. Line()
Using namespaces // Namespace Declaration using System; // Program start class public class Hello. World { // Main begins program execution static void Main() { // This is a single line comment /* This is a multiple line comment */ Console. Write. Line("Hello World!"); } }
Operators, Types, and Variables C# is a strongly “typed" language (aka “type-safe”. ) - All operations on variables are performed with consideration of what the variable's “type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.
Types C# simple types consist of the Boolean type and three numeric types (integer, floating-point and decimal) and the String type. The pre-defined reference types are object and string, where object is the ultimate base class of all other types. Boolean type - Boolean types are declared using the keyword, bool. They have two values: true or false. These are keywords. E. g. bool gaga = true;
Data Types • Common C# data types – – – The “root” type Logical Signed Integer Unsigned Integer Floating-point Text object bool short, int, long ushort, uint, ulong float, double, char, string
The Object Type • The object type: – Is declared by the object keyword – Is the base type of all other types – Can hold values of any type object data. Container = 5; Console. Write("The value of data. Container is: "); Console. Write. Line(data. Container); data. Container = "Five"; // same variable Console. Write("The value of data. Container is: "); Console. Write. Line(data. Container);
All types are compatible with object - A variable of any type can be assigned to variables of type object - All operations of type object are applicable to variables of any type.
Types, Classes, and Objects • Data Type – C# has more than one type of number • int type is a whole number • Floating-point types can have a fractional portion • Types are actually implemented through classes – One-to-one correspondence between a class and a type – Simple data type such as int is implemented as a class
Integer type In C#, an integer is a category of types. They are whole numbers, either signed or unsigned.
Floating-Point and Decimal Types A C# floating-point type is either a float or double. They are used any time you need to represent a real number. The decimal type should be used when representing financial or money values.
Caution with Floating-Point Comparisons • Sometimes problems can happen when comparing floating-point number values due to rounding errors. – Comparing floating-point numbers should not be made directly with the == (equality) operator • Example: double a = 1. 0; double b = 0. 33; double sum = 1. 33; This strange syntax will be explained shortly! bool equal = (a+b == sum); // Not necessarily true! Console. Write. Line("a+b={0} sum={1} equal={2}", a+b, sum, equal);
int student. Count; // number of students in the class int age. Of. Student = 20; // age - originally initialized to 20 int number. Of. Exams; // number of exams int courses. Enrolled; // number of courses enrolled double extra. Person = 3. 50; // extra. Person originally set // to 3. 50 double average. Score = 70. 0; // average. Score originally set // to 70. 0 double price. Of. Ticket; // cost of a movie ticket double grade. Point. Average; // grade point average float total. Amount = 23. 57 f; // note the f must be placed after // the value for float types
Example • An example of using types in C# – Declare before you use (compiler enforced) – Initialize before you use (compiler enforced) declarations public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; declaration + initializer int x; int y = x * 2; . . . error, x not set } }
Boolean Variables • Based on true/false • Boolean type in C# → bool • Does not accept integer values such as 0, 1, or -1 bool undergraduate. Student; bool more. Data = true;
Boolean Values – Example • Example of boolean variables taking values of true or false: int a = 1; int b = 2; bool greater. AB = (a > b); Console. Write. Line(greater. AB); // False bool equal. A 1 = (a == 1); Console. Write. Line(equal. A 1); // True
Data Type char The character data type: - Represents symbolic information – single quotes ‘… ‘ - Is declared by the char keyword - Gives each symbol a corresponding integer code - Has a ' ' default value
The String Data Type • The string data type: – Represents a sequence of characters – Is declared by the string keyword – Has a default value null (no value) – Really a pre-defined class • Strings are enclosed in double quotes: “…” • Strings can be concatenated – Using the + operator string s = “SWU – “ + “ICo. SCIS Project";
Saying Hello – Example • Concatenating the two names of a person to obtain his full name using + string first. Name = "Ivan"; string last. Name = "Ivanov"; Console. Write. Line("Hello, {0}!n", first. Name); string full. Name = first. Name + " " + last. Name; Console. Write. Line("Your full name is {0}. ", full. Name);
Class System. String Can be used as standard type string s = “ICo. SCIS"; Note • Can be concatenated with +: “SWU " + s; • Can be indexed: s[i] • String length: s. Length • String values can be compared with == and !=: if (s == “SWU"). . . • Class String defines many useful operations: Compare. To, Index. Of, Starts. With, Substring, . . .
Data Constants • Add the keyword const to a declaration • Value cannot be changed • Standard naming convention – identifier usually uppercase characters Syntax const type identifier = expression; Example const double TAX_RATE = 0. 0675; const int SPEED = 70; const char HIGHEST_GRADE = ‘A’;
Mixed Expressions – Different Types • Explicit type coercion – Cast Syntax: (type) expression exam. Average = (exam 1 + exam 2 + exam 3) / (double) count; int value 1 = 0, another. Number = 75; double value 2 = 100. 99, another. Double = 100; value 1 = (int) value 2; // value 1 = 100 value 2 = (double) another. Number; // value 2 = 75. 0
Identifiers • Identifiers may consist of – Letters – Digits [0 -9] – Underscore "_" • Identifiers – Can begin only with a letter or an underscore – Cannot be a C# keyword
Identifiers – Examples • Examples of correct identifiers: int New = 2; // Here N is capital int _2 Pac; // This identifier begins with _ string greeting = "Hello"; int n = 100; // Undescriptive int number. Of. Clients = 100; // Descriptive // Overdescriptive identifier: int number. Of. Private. Client. Of. The. Firm = 100; • Examples of incorrect identifiers: int new; int 2 Pac; // new is a keyword // Cannot begin with a digit
Initializing Variables • Initializing – Must be done before the variable is used! • Several ways of initializing: – By using the new keyword – By using a literal expression – By assigning an already initialized variable
Initialization – Examples • Example of some initializations: // The following would assign the default // value of the int type to num: int num = new int(); // num = 0 // This is how we use a literal expression: float height. In. Meters = 1. 74 f; // Here we use an already initialized variable: string greeting = "Hello World!"; string message = greeting;
int number. Of. Minutes, count, min. Int. Value; char first. Initial, year. In. School, punctuation; number. Of. Minutes = 45; count = 0; min. Int. Value = -2147483648; first. Initial = ‘B’; year. In. School = ‘ 1’; enter. Key = ‘n’; // newline escape character
Statements in C# • C# supports the standard assortment … • assignment • function • conditional – if, if-else, switch • iteration – for, while, do-while • control flow – return, break, continue
Console Input/Output Methods Writing to screen Methods are members of Console class Console. Write. Line() - Writes to screen followed by newline Console. Write( ) - Writes to screen without newline
Reading from keyboard • Console. Read( ) reads a single character from the keyboard • Console. Read. Line( ) reads a string of characters from the keyboard – Until the enter key is pressed – Character string has type string – Must use a conversion method to convert the input string to the proper type!
Console. Write(…) Printing a variable int a = 15; . . . Console. Write(a); // 15 – next print stays on same line
• Printing using a formatting string double a = 15. 5; int b = 14; . . . Console. Write("{0} + {1} = {2}", a, b, a + b); // 15. 5 + 14 = 29. 5
Formatting String Example Console. Write("{0} + {1} = {2}", a, b, a + b); Formatting string: "{0} + {1} = {2}“ The numbers refer to the three variables a, b, a + b The numbers are “placeholders” for the variables. The numbers start from 0. 0–a 1–b 2–a+b
Console. Write. Line(…) Printing a string variable string str = "Hello C#!"; . . . Console. Write. Line(str); Printing more than one variable using a formatting string name = “Elena"; int year = 1980; . . . Console. Write. Line("{0} was born in {1}. ", name, year); // Elena was born in 1980. Next printing will start from the new line
Reading Numeric Types • Numeric types can not be read directly from the console • To read a numeric type, do the following: 1. Read a string value 2. Convert it to the required numeric type Example int. Parse(string) – Converts a string to int string str = Console. Read. Line() int number = int. Parse(str); Console. Write. Line("You entered: ", number);
Converting Strings to Numbers • Types have a method Parse() for extracting the numeric value from a string – double. Parse(string ) – int. Parse(string ) – char. Parse(string ) – bool. Parse(string ) • Expects string argument – Argument must be a number – string format • Returns the number (or char or bool)
Example public static void Main() { int a = int. Parse(Console. Read. Line()); int b = int. Parse(Console. Read. Line()); Console. Write. Line("{0} + {1} = {2}", a, b, a+b); Console. Write. Line("{0} * {1} = {2}", a, b, a*b); } float f = float. Parse(Console. Read. Line()); Console. Write. Line("{0} * {1} / {2} = {3}", a, b, f, a*b/f);
using System; class Square. Input. Value { static void Main( ) { string input. String. Value; double a. Value, result; Console. Write(“Enter a value to be squared: ”); input. String. Value = Console. Read. Line( ); a. Value = double. Parse(input. String. Value); result = Math. Pow(a. Value, 2); Console. Write. Line(“{0} squared is {1}”, a. Value, result); } }


