INF160Lec03 PL C#

advertisement
INF160 IS Development Environments
AUBG, COS dept
Lecture 03
Title:
Tutorial Introduction to C#
(Extract from Syllabus)
1
Lecture Contents:




C# program – general definition/description
C# program – basic structure
C# program – demo example
Detailed description of C# as a conventional
programming language
2
To students with skills in C#

















Write a program - Tester for factorial, greatest common divisor, Fibonacci series number
PRELUDE:
To compute Fibonacci series nnumber you need a method like this header
int Fibonacci( int n )
{
…
}
To compute factorial you need a method like this header
int Factorial( int n )
{
…
}
To compute greatest common divisor you need a method like this header
int GCD( int m, int n )
{
…
}
3
Program – definition/description
 Program: An organized list of instructions that, when executed,
causes the computer to behave in a predetermined manner.
 C# program: Collection of one or more classes, one of which has
method titled public static void Main(string[] args).
 C# class: mechanism that allows to combine data and operations
/named methods/ on that data into a single unit.
 C# method: Set of instructions designed to accomplish a
specific task.
 In OOD the final C# program is a collection of interacting
objects /instances of classes/.
4
C# Program – basic structure
 C# programs can consist of one or more files.
 Each file can contain zero or more namespaces.
 A namespace can contain types such as classes,
structs, interfaces, enumerations, and
delegates, in addition to other namespaces.
 The following is the skeleton of a C# program
that contains all of these elements.
5
‘Review:VB Program – basic structure
<Imports declarations>
<Module heading>
Sub Main()
<definition/declaration statements>
<executable statements>
End Sub
<Module end delimiter>
Review
On
VBASIC
‘ Review: VB program – demo example
Imports System
Module thisModule
Sub Main()
Console.WriteLine(“Hello, World!”)
Console.ReadKey()
End Sub
6
End Module
// Review: C++ Program – basic structure
Review
<preprocessor directives>
using namespace <region>;
On
void main()
{
C++
<definition/declaration statements>
Native code
<executable statements>
}
// Review: C++ Program – demo example
#include <iostream>
using namespace std;
void main( )
{
cout << “\nHello, World!”;
system(“pause”);
7
}
// Review: C++ Program – basic structure
Review
<preprocessor directives>
using namespace <region>;
On
void main()
C++
{
<definition/declaration statements>
Managed code
<executable statements> // Review: C++ Program – demo example
}
#include "stdafx.h"
using namespace System;
int main( )
{
Console::WriteLine("Hello World");
Console::ReadKey();
return 0;
8
}
// C# Program – basic structure
using System;
namespace YourNamespace
{
class YourClass
{
}
interface IYourInterface
{
}
delegate int YourDelegate();
}
class YourMainClass
{
static void Main(string[] args)
{
//Your program starts here...
}
}
New:
C#
// C# Program – demo example
using System;
namespace MyProject
{
public class Hello
{
public static void Main(string[] args)
{
Console.WriteLine("Hello world in C#");
Console.ReadLine();
}
}
}
9
.
Detailed description
of
C# as Conventional Prog Lan
10
Lecture Contents (new):
• Why C# (instead intro)
• Anatomy of a C# program
–
–
–
–
–
Sample source text
Namespaces
Comments
Names – identifiers, reserved words, modifiers
Classes – data fields, methods (statements, blocks of statements )
• Components of a C# program
–
–
–
–
–
–
–
Data – by category
Data – by type
Expressions (incl. operands & operators)
Statements
Routines (member functions - methods)
I/O facilities
Data collections – arrays, etc
• Demo programs - examples
11
Why C#
• Conforms closely to C and C++. Has the added power of C++
• Has the rapid graphical user interface (GUI) features of
previous versions of Visual Basic
• Has the object-oriented class libraries similar to Java
• Can be used to develop a number of applications
–
–
–
–
–
–
–
Software components
Mobile applications
Dynamic Web pages
Database access components
Windows desktop applications
Web services
Console-based applications
C# Programming: From Problem Analysis to Program Design
12 12
C# Plang provides features, such as:










OOP, Event driven programming, visual programming
strings,
graphics,
graphical-user-interface (GUI) components,
exception handling,
multithreading,
multimedia (audio, images, animation and video),
file processing,
database processing,
Internet and WWW-based client/server networking and distributed computing.
• C# programs are created using Integrated Development Environment
(IDE).
• With the IDE, a programmer can create, run, test and debug C#
programs.
• The process of rapidly creating an application using an IDE is
typically referred to as Rapid Application Development (RAD).
13
Anatomy of a C# program:
Sample source text
14
Syntax for simple C# program
// Program start class
using System;
namespace space_name
{
public class class_name
{
// Main begins program execution
public static void Main(string[] args)
{
// implementation of method
}
}
}
15
Hello World!
Console Application
16
Namespaces. The using directive
• using System; directive is generated by the Visual Studio IDE
and declares that the program uses features in the System
namespace.
• A namespace groups various C# features into related
categories.
• C# programmers can use the rich set of namespaces provided
by the .NET framework. The namespaces that are defined in the
.NET Framework contain preexisting code known as the .NET
Framework Class Library Over 2,000 classes included.
• An example of one of the features in namespace System is
Console.
• In console applications, we use Console.method when we want
to handle standard input, output, and error streams for our
applications
17
Namespace
• Namespaces provide scope for the names defined
within the group
• Groups semantically related types under a single
umbrella
• System: most important and frequently used
namespace
• Can define your own namespace
• Used to avoid naming collisions
• Each namespace enclosed in curly braces: { }
C# Programming: From Problem Analysis to Program Design
18 18
Namespace (continued)
Predefined namespace
(System) – part of
.NET FCL
From Example 1-1
line 1
line 2
line 3
line 4
// This is traditionally the first program written.
using System;
namespace HelloWorldProgram
{
line 12
}
User-defined
namespace
Body of userdefined namespace
C# Programming: From Problem Analysis to Program Design
19 19
Concole.WriteLine
• In C# statements we normally precede each class name
with its namespace name and a period.
• For example, line of source text would normally be:
System.Console.WriteLine( "Welcome to C# Programming!" );
for the program to run correctly.
• The using System; directive eliminates the need to
specify explicitly the namespace System when using
classes in the namespace. This can save time and
confusion for programmers.
20
Anatomy of a C# program: classes
21
Line 6-12: Class Welcome1
• Line 6-12 class (these lines collectively are called a
class definition).
• C# programs consist of pieces called classes,
• Classes are logical groupings of members (e.g.,
methods) that simplify program organization. These
methods (which are like functions in procedural
programming languages) perform tasks and return
information when the tasks are completed.
• A C# program consists of classes and methods
created by the programmer and of preexisting
classes found in the Framework Class Library.
22
Class Welcome1
• The class keyword begins a class definition in C#
and is followed immediately by the class name
(Welcome1, in this example).
• The left brace ({) at line 7 begins the body of the
class definition.
• The corresponding right brace (}) at line 12 ends the
class definition.
• Notice that lines 8–11 in the body of the class are
indented. This is one of the spacing conventions .
Indentation improves program readability
23
Anatomy of a C# program:
classes (methods)
• C# class definitions normally contain one or
more methods (member functions) and C#
applications contain one or more classes.
• For a C# console or Windows application,
exactly one of those methods must be called
Main, and it must be defined as shown:
static void Main(string[] args)
24
Main
• These applications begin executing at Main,
which is known as the entry point of the
program.
• The parentheses after Main indicate that
Main is a program building block, called a
method.
25
26
More Choices
public static void Main() {
...
}
public static int Main() {
...
return 0;
}
public static int Main(string[] args) {
...
return 0;
}
27
Syntax of body method
• The left brace ({) on line 9 begins the body of the
method definition (the code which will be executed
as a part of our program).
• A corresponding right brace (}) terminates the
method definition’s body (line 11).
• The body method includes/contains statements.
28
Console.WriteLine(“Welcome to C# programming!”);
• The entire line, including Console.WriteLine, its
argument in the parentheses ("Welcome to C#
Programming!") and the semicolon (;), is called a
statement.
• Every statement must end with a semicolon (known
as the statement terminator).
• When this statement executes, it displays the
message Welcome to C# Programming! in the
console window
29
Types of Statements
• Declaration statements - describe the data
the function needs:
float miles, kms;
const float KM_PER_MILE = 1.609;
• Executable statements - specify the actions
the program will take:
Console.WriteLine(“Welcome to C# programming!”);
30
Anatomy of a C# program:
statements, blocks of statements
• {…}
• Block
• Compound statement
31
Names: Identifiers
• The name of the class is known as an identifier, which is a series of
characters consisting of letters, digits, underscores ( _ ) and “at”
symbols (@).
• Identifiers cannot begin with a digit and cannot contain spaces.
• Examples of valid identifiers are Welcome1, _value, m_inputField1
and button7.
• The name 7button is not a valid identifier because it begins with a digit
• The name input field is not a valid identifier because it contains a
space.
• The “at” character (@) can be used only as the first character in an
identifier.
• C# is case sensitive — uppercase and lowercase letters are
considered different letters.
32
Reserved Words in C#
Keywords (or reserved words) are reserved for use by
C# and always consist of lowercase letters.
C# Programming: From Problem Analysis to Program Design
33 33
Reserved Words in C# (continued)
• Contextual keywords
• As powerful as regular keywords
• Contextual keywords have special meaning only
when used in a specific context; other times they
can be used as identifiers
C# Programming: From Problem Analysis to Program Design
34 34
Data
Java Programming: From Problem Analysis to Program Design, 4e
35 35
Components of a C# program
Data – by category
• Literals
• Variables
• Constants
36
Constant Definition
• Named Constant definitions have the following
syntax:
const datatype name = value;
• To define a constant to hold the value of pi, for
example, you could use a statement such as
this:
const double c_pi = 3.14159265358979;
37
Declaring Variables
datatype variablename = initialvalue;
• You don’t have to specify an initial value for a variable, although
being able to do so in the declaration statement is useful. To
create a new string variable and initialize it with a value, for
example, you could use two statements, such as the following:
string strName;
strName = “Matt Perry”;
• However, if you know the initial value of the variable at design
time, you can include it on the declaration statement, like this:
string strName = “Matt Perry”;
• Note, however, that supplying an initial value doesn’t make this a
constant; it’s still a variable, and the value of the variable can be
changed at any time.
38
Components of a C# program:
Data – by type
• Value types
• Reference types
39
Value type
- where a variable X contains a value type, it directly
contains an entity with some value. No other variable Y can
directly contain the object contained by X (although Y might
contain an entity with the same value).
Reference type
- where a variable X contains a reference type, what it
directly contains is something that refers to an object.
Another variable Y can contain a reference to the same
object referred to by X.
Reference types actually hold the value of a memory address
occupied by the object they reference.
40
41
Predefined (Data) Types
•
C# predefined types
–
–
–
–
–
–
The “root”
Logical
Signed
Unsigned
Floating-point
Textual
•
object
bool
sbyte, short, int, long
byte, ushort, uint, ulong
float, double, decimal
char, string
Textual types use Unicode (16-bit characters)
42
All types are compatible with object
- can be assigned to variables of type object
- all operations of type object are applicable to them
43
Predefined Data Types
• Common Type System (CTS)
• Divided into two major categories
Figure 2-3 .NET common types
C# Programming: From Problem Analysis to Program Design
44 44
Value and Reference Types
Figure 2-4 Memory representation for value and reference types
C# Programming: From Problem Analysis to Program Design
45 45
Value Types
• Fundamental or primitive data types
Figure 2-5 Value type hierarchy
C# Programming: From Problem Analysis to Program Design
46 46
Integer type
In C#, an integer is a category of types. They are whole
numbers, either signed or unsigned.
47
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.
Decimal types should be used when representing financial or
money values.
48
The String Type
A string is a string of text characters.
The keyword string is an alias for the class System.String.
Either may be used to define a string variable.
string aa = "Sofia";
String bb = "BG";
System.String cc = " AA ";
A string literal is just some text enclosed with double quotes.
E.g. “This is a string”
There is a char type used to represent one Unicode character.
49
Class System.String
Can be used as standard type string
string s = “AUBG";
Note
• Strings are immutable (use class StringBuilder if you
want to extend a string)
• Can be concatenated with +: “COS @ " + s;
• Can be indexed: s[i]
• String length: s.Length
• Strings are reference types  reference semantics in
assignments.
• But their values can be compared with == and !=:
if (s == "AUBG") ...
• Class String defines many useful operations:
CompareTo, IndexOf, StartsWith, Substring, ...
50
Casting Data from
One Data Type to Another
51
52
Expressions (operands and operators)
Java Programming: From Problem Analysis to Program Design, 4e
53 53
Components of a C# program:
Expressions (operands)
• Operands
–Literal Values
–Constants
–Variables – scalar or indexed
–Structure member
–Function call
–Sub expression like ( … )
54
C# Operators
The table on the following slide describes the allowable
operators, their precedence, and associativity.
Left associativity means that operations are evaluated
from left to right.
Right associativity mean all operations occur from right to
left, such as assignment operators where everything to the right
is evaluated before the result is placed into the variable on the
left.
55
56
Mixed Expressions
• Implicit type coercion
– Changes int data type into a double
– No implicit conversion from double to int
Figure 2-14 Syntax error generated for assigning a double to an int
C# Programming: From Problem Analysis to Program Design
57 57
Mixed Expressions (continued)
• Explicit type coercion
– Cast
– (type) expression
– examAverage = (exam1+exam2+exam3) / (double) count;
Int
value1 = 0,
double value2 = 100.99,
anotherNumber = 75;
anotherDouble = 100;
value1 = (int) value2;
// value1 = 100
value2 = (double) anotherNumber; // value2 = 75.0
C# Programming: From Problem Analysis to Program Design
58 58
Components of a C# program:
Executable Statements
59
Statements in C#
• C# supports the standard assortment …
• assignment
• subroutine and function call
• conditional
– if, switch
• iteration
– for, while, do-while, foreach
• control Flow
– return, break, continue, goto
60
Passing Literal Values to a Variable
• The syntax of assigning a literal value (a hard-coded value such
as 6 or “guitar”) to a variable depends on the variable’s data
type.
• For strings, you must pass the value in quotation marks, like
this:
strCollegeName = “Bellevue University”;
• There is one caveat when assigning literal values to strings:
Visual C# interprets slashes (\) as being a special type of
escape sequence. If you pass a literal string containing one or
more slashes to a variable, you get an error. What you have to
do in such instances is preface the literal with the symbol @, like
this:
strFilePath = @”c:\Temp”;
• When Visual C# encounters the @ symbol after the equal sign
as shown in the preceding example, it knows not to treat slashes
61
in the string as escape sequences.
Decision Structures - Selection
Same syntax for C++, C#, and Java
if (condition) statement;
if (condition) statement1; else statement2;
switch statement
62
Examples
if (x == valueOne)
{
Console.Writeline("x is ");
Console.Writeline( x );
}
if (x == valueOne)
Console.Writeline("x is 100");
else
Console.Writeline("x is not 100");
63
Switch construct
Same syntax for C++, C#, and Java
switch can only be used to compare an expression with
different constants.
The types of the values a switch statement operates on can be
booleans, enums, integral types, and strings (null is
acceptable as a case label).
No fall-through!
- Every statement sequence in a case must be
terminated with break (or return, goto, throw).
If no case label matches  default
If no default specified  continuation after the switch
statement
64
switch (x)
{
case 5: Console.Writeline("x is 5");
break;
case 99: Console.Writeline("x is 99");
break;
default: Console.Writeline("value of x unknown"); break;
}
switch(country) {
case"Germany":
case"Austria":
case"Switzerland":
language = "German"; break;
case"England":
case"USA":
language = "English"; break;
case null:
Console.WriteLine("no country specified"); break;
default:
Console.WriteLine("don't know language of", country);break;
}
65
66
Loops
Same syntax for C++, C#, and Java
for (initialization; condition; in(de)crement)
{statement;}
while (Boolean expression)
{statements}
do
{statements}
while (Boolean expression)
foreach statement
67
Loops
for (int n=10; n>0; n--)
{
Console.Write( n );
Console.Write(", ");
}
while ( x > 1 )
{
Console.Writeline("x is ");
x--;
}
Console.Writeline( x );
do
{
Console.Writeline("x is "); Console.Writeline( x );
x--;
} while (x !=1 );
68
foreach statement: For iterating over collections and arrays.
foreach can not be used to change the contents of the array
foreach (Type variableName in container)
{
// statements;
}
// array traverse using foreach
int[] a = {3, 17, 4, 8, 2, 29};
foreach (int x in a) sum += x;
// string traverse using foreach
string s = "Hello";
foreach (char ch in s) Console.WriteLine(ch);
69
Control flow - return
Java Programming: From Problem Analysis to Program Design, 4e
70 70
Components of a C# program:
Routines (methods)
• Main method Already discussed in section
classes(methods(statements))
• Same as in C++, Java
71
Components of a C# program:
Routines (methods)
static void Main(string[] args)
{
Console.WriteLine("Summing numbers result is = {0}", sum(21,30));
Console.WriteLine("Summing numbers result is = {0}", sum(501, 630));
Console.WriteLine("Multiplying numbers result is = {0}", product(1,10));
}
static int sum(int m, int n)
{
int i, suma = 0;
if (m > n) return -1;
if (m == n) return m;
for (i=m ; i<=n ; i++) suma += i;
return suma;
}
static int product(int m, int n)
{
int i, res = 1;
if (m > n) return -1;
if (m == n) return m;
for (i = m; i <= n; i++) res *= i;
return res;
}
72
Components of a C# program:
Routines (methods)
static void Main(string[] args)
{
Console.WriteLine("Summing numbers result is = {0}", sum(21,30));
Console.WriteLine("Summing numbers result is = {0}", sum(501, 630));
Console.WriteLine("Multiplying numbers result is = {0}", product(1,10));
}
static int product(int m, int n)
{
int i, res = 1;
if (m > n) return -1;
if (m == n) return m;
for (i = m; i <= n; i++) res *= i;
return res;
}
static int sum(int m, int n)
{
int i, suma = 0;
if (m > n) return -1;
if (m == n) return m;
for (i=m ; i<=n ; i++) suma += i;
return suma;
}
73
Components of a C# program:
I/O
74
Console Input
The Console class provides basic support for applications that input
characters.
Data is read from the standard input stream
int x;
string alpha;
alpha = Console.ReadLine(); // will read the input from the keyboard
x = System.Convert.ToInt32(alpha); // and save it in variable x
Console Output
Output is managed by a class named Console. This Console class has a
method WriteLine() which takes a string (a set of characters) and writes
it to the standard output.
Console.WriteLine("Text");
Console.WriteLine(120);
// prints “Text” to the screen
// prints value 120 on screen
Console.WriteLine(x.ToString());
// prints the content of x on screen
75
76
77
Input Data
• You can eliminate the need for string
variables firstNumber and secondNumber
by combining the input and conversion
operations as follows:
int number1;
number1 = Int32.Parse( Console.ReadLine() );
78
WriteLine format
• After performing the calculation, line 33 displays the result of
the addition. In this example, we want to output the value in a
variable using method WriteLine. Let us discuss how this is
done.
• The comma-separated arguments to Console.WriteLine
"\nThe sum is {0}.", sum
use {0} to indicate a placeholder for a variable’s value.
• If we assume that sum contains the value 117, the expression
evaluates as follows:
79
80
Components of a C# program:
Data collections
• Arrays
• Records (C-like structs)
81
Data Collections
Typical popular Data collections:
• Arrays
• Structures
Detailed discussion on arrays and structures
presented in separate lectures later
82
Demo Programs
D
83
Demo Programs
Demonstrate end-of-file controlled loop using standard
input from the keyboard and standard output to the
screen
Solution to implement in a version:
as managed code console application
Problem:
To accumulate sum of stream of input integers
terminated by end-of-data (CTRL/Z) indicator 84
Demo Program – Managed Code Only
// C# demo program, standard Input (keyboard) / Output (screen)
// Int Console.Read(),
// String Console.ReadLine() // ReadKey()
// Methods Convert.ToInt32(string), etc …
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string pom;
while ((pom = Console.ReadLine()) != null)
{
sum += Convert.ToInt32(pom);
}
Console.WriteLine("Final sum = {0}",sum);
}
}
}
85
Thank You
For
Your Attention!
86
Download