Advanced Programming C# Introduction 1. C# Genealogy FortranAlgol 68CC++C# Cobol Eiffel JavaAda...
-
Upload
thomas-carson -
Category
Documents
-
view
229 -
download
3
Transcript of Advanced Programming C# Introduction 1. C# Genealogy FortranAlgol 68CC++C# Cobol Eiffel JavaAda...
Advanced Programming
C#
Introduction
1
C# Genealogy
Fortran Algol 68 C C++ C#
Cobol
Eiffel
JavaAda 95PL/I Pascal
ElementaryProcedural
AdvancedProcedural
SpecialProcedural
ObjectOriented
AdvancedObject
Oriented
Ada 83
3
•A program is a machine-compatible representation of an algorithm
•If no algorithm exists for performing a task,
then the task can not be performed by a machine
•Programs and algorithms they represent
collectively referred to as Software
Program
4
Programming Languages
Machine language
Strings of 0 and 1, machine dependent
Assembly language
•English like abbreviations representing elementary operations
•Assemblers needed to convert assembly into machine language
High-level languages (C, C++, Java, …)
•Single statements accomplish substantial tasks
•Compiler needed to convert the program into machine language
•Some languages are interpreted (executed without the need for compilation)
5
Example Machine Code Fragment
177312 137272 001400 026400 017400 000012 000007 004420010400 011000 000010 005023 012000 012400 000010 003426013400 000007 000430 003000 064474 064556 037164 000001024003 053051 000001 041404 062157 000545 007400 064514062556 072516 061155 071145 060524 066142 000545 002000060555 067151 000001 024026 046133 060552 060566 066057067141 027547 072123 064562 063556 024473 000526 005000067523 071165 062543 064506 062554 000001 046014 067151067543 067154 065056 073141 006141 004000 004400 000007006031 015000 015400 000001 040433 070440 067565 062564060552 060566 064457 027557 071120 067151 051564 071164060545 000555 003400 071160 067151 066164 000556 012400046050 060552 060566 066057 067141 027547 072123 064562063556 024473 000126 000041 000006 000007 000000 000000000002 000001 000010 000011 000001 000012 000000 000035000001 000001 000000 025005 000267 130401 000000 000400005400 000000 003000 000400 000000 003400 004400 006000006400 000400 005000 000000 030400 001000 000400 000000010400 000262 011002 133003 002000 000262 011002 133005002000 000261 000000 000001 000013 000000 000016 000003000000 000016 000010 000020 000020 000021 000001 000016000000 000002 000017
A number specifies what action the computer should take.
6
Example Assembly Code Fragment
movl (%edx,%eax), %ecx movl 12(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax movl (%edx,%eax), %eax fldl (%ecx) fsubl (%eax) movl 8(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax movl (%edx,%eax), %ecx movl 12(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax
Symbols to help programmers to remember the words.
7
Programming Languages
•Examples of High-level languages
•FORTRAN (FORmula TRANslator) in 1950s
scientific and engineering applications
•COBOL (Common Business Oriented language) in 1959
Commercial applications for manipulation of large amounts of data
•BASIC (Beginner’s All Purpose Symbolic Instruction Code)
Familiarize novices with programming techniques (in mid-1960s)
•Pascal (17th century mathematician Blaise Pascal) in 1971
Teaching structured programming in academic environments
8
Programming Languages
•C
Bell labs Dennis Ritchie, 1973
•C++
Bjarne Stroustrup, 1980
Hybrid OOP
•Java
Sun Microsystems (formally announced in May 1995)
Pure OOP
Web programming
What is C#?
• C# (pronounced "C sharp") is an object-oriented language that is used to build applications for the Microsoft .NET platform
• C# is designed by Microsoft to combine the power of C/C++, Java and the productivity of Visual Basic
• The goal of C# and the .NET platform is to shorten development time - by allowing developers to spend their time working on the
application logic instead of low level programming details
10
Why C#?
support so-called safe internet programming
simpler than other object-oriented languages [C++]
safe and robust --- no core dump or dead console
good graphics package
related to C and C++
good client-server and network support
good for your future job
C# A component oriented language
C# is the first “component oriented” language Component concepts are first class:
Properties, methods, events Design-time and run-time attributes Integrated documentation using XML
Enables one-stop programming No header files, IDL, etc. Can be embedded in web pages
C# Everything really is an object
Traditional views C++, Java: Primitive types are “magic” and do not
interoperate with objects Smalltalk, Lisp: Primitive types are objects, but at
great performance cost
C# unifies with no performance cost Deep simplicity throughout system
Improved extensibility and reusability New primitive types: Decimal, SQL… Collections, etc., work for all types
13
Learning C#
Just like learning any new language
Syntax: “new words”
Grammar: how to put them together
Programming: telling a coherent story
Library: use plots already written
Picking up Java and C++ after C# should be easy!
14
Programming Languages C#
Microsoft announced the .NET initiative (June 2000) and C#
.NET enables web-based applications to be distributed to a great variety of devices and desktop computers
Allows applications created in various programming languages to communicate with each other
Designed to ease migration to .NET (roots in C and C++)
Event-driven, fully OO visual programming language
Microsoft’s .NET Technologies
Many languages run on .NET framework C#, C++, J#, Visual Basic even have Python (see IronPython)
16
Example C++/C#/Java Code Fragment
bool DetermineNeighbor(int i, int j) { double distanceX = (nodes[i].x - nodes[j].x); double distanceY = (nodes[i].y - nodes[j].y); double distanceSquare = disx * disx + disy * disy; double distance = sqrt(distanceSquare); if (distance < radius)
return true; else
return false;}
You do not need to understand the exact meaning of this program, just the feeling.
Visual StudioHTML 5 / CSS 3 / Javascript HTML 5 / CSS
Full HTML 5 and CSS 3 specs supported
Quirks for downlevel browsers fully supported CSS and JavaScript now first class citizens in editor DOCTYPE
JavaScript Based on Chakra engine in IE 9 Directly tell us which JS files to provide intellisense
C# compiling.
C# is executed indirectly through an abstract computer architecture called the CLR. CLR => Common
Language Runtime. Abstract, but well
defined. C# programs are
compiled to an IL. Also called MSIL, CIL
(Common Intermediate Language) or bytecode.
http://msdn2.microsoft.com/en-us/library/z1zx9t92(VS.80).aspx
Compiling C# Source Code
• C# file names have the extension .cs
• To create the IL file, we need to compile the .cs file using the csc (using the command line), followed by the name of the source file
• The result is a file with the same name but the .exe extension, which is called an assembly
• The assembly file contains all the information that the common runtime needs to know to execute the program
• We can also create multi-file assemblies using an assembly linker, see the following link for more details:
http://longhorn.msdn.microsoft.com/lhsdk/ndp/tskhowtobuildmultfileassembly.aspx
20
C# Compilation and Execution
C# sourcecode
MSIL
C#compiler
Machinecode
Just in timecompiler
21
C# and Language Comparison60% Java, 10% C++, 10% VB, 20% new
As in Java Object-orientation
(single inheritance) Namespaces
(like packages) Interfaces Strong typing Exceptions Threads Garbage collection Reflection Dynamic loading
of code
As in C++ Operator overloading Pointer arithmetic in
unsafe code Some syntactic
details As in VB
Properties Events RAD development
22
OOP
•Structured programming versus OOP
•Objects have properties (attributes) and perform actions
Objects are defined in classes (represent groups of related objects)
•Programs are more understandable
better organized programs
23
Introduction to C#
Console applications No visual components
Only text output Two types
MS-DOS prompt (Used in Windows 95/98/ME) Command prompt (Used in windows 2000/NT/XP)
Windows applications Forms with several output types Contain Graphical User Interfaces (GUIs)
24
New Project dialog.
25
New Project dialog.
New project dialogue C# .NET project
Group of related files, images, and documentations
C# .NET solution Group of projects creating one or a group of
applications Windows Applications
Anything that runs in the Windows OS Microsoft Word Microsoft Internet Explorer
26
27
Simple Program
A First C# Program: 'Hello World'
using System; public class HelloWorld { public static void Main(string[] args) { // This is a single line comment /* This is a multiple line comment */
Console.WriteLine("Hello World"); } }
29
Simple Program
Execution of the Welcome1 program.
30
Windows Application
tabs
menu title bat
menu bar
active tab Solution Explorer
Properties window
Form (windows application)
31
Windows Application
IDE after a new project The form
Grey rectangle in window Represents the project’s window Part of the GUI or Graphical User Interface
Graphical components for user interaction User can enter data (input) Shows user instructions or results (output)
Tabs One tab appears for each open document Used to save space in the IDE
32
Simple Program: Displaying Text and an Image
33
Simple Program: Displaying Text and an Image
Creating a new Windows application.
Project name
Project location Click to change project location
Project type
34
35
36
Simple Program: Displaying Text and an Image
Setting the form’s Text property.
Name and type of object
Property value
Selected property
Property description
37
Simple Program: Displaying Text and an Image Resize the form
Click and drag one of the forms size handles Enables handles are white Disables handles are gray
The grid in the background will not appear in the solution Change the form’s background color
The BackColor determines the form’s background color Dropdown arrow is used to set the color
Add a label control to the form Controls can be dragged to the form Controls can be added to the form by double clicking The forms background color is the default of added controls
38
Simple Program: Displaying Text and an Image
Form with sizing handles.
grid
Mouse pointer over a sizing handle
Enabled sizing handle
Disabled sizing handle
Title bar
39
Simple Program: Displaying Text and an Image
Changing property BackColor.
Down arrow
Current color
Custom palette
40
Simple Program: Displaying Text and an Image
Adding a new label to the form.
Label control
New background color
41
Simple Program: Displaying Text and an Image Set the label’s text
The Text property is used to set the text of a label The label can be dragged to a desired location Or Format > Center In Form > Horizontal can also be
used to position the label as in in this example Set the label’s font size and align text
The Font property changes the label’s text (Fig. 2.23) The TextAlign property to align the text
Add a picture box to the form Picture boxes are used to display pictures Drag the picture box onto the form
42
Simple Program: Displaying Text and an Image
Label in position with its Text property set.
Label centered with updated Text property
43
Simple Program: Displaying Text and an Image
Properties window displaying the label’s properties.
Ellipsis indicate dialog will appear
44
Simple Program: Displaying Text and an Image
Font window for selecting fonts, styles and sizes.
Font size
Current font
45
Simple Program: Displaying Text and an Image
Centering the text in the label.
Text alignment option
Top-center alignment option
46
Simple Program: Displaying Text and an Image
Inserting and aligning the picture box.
Updated Label
New PictureBox
47
Simple Program: Displaying Text and an Image Insert an image
The Image property sets the image that appears Pictures should be of type .gif, .jpeg, or .png
The picture box is resizable to fit the entire image Save the project
In the Solution Explorer select File > Save Using Save All will save the source code and the project
Run the project In run mode several IDE features are disabled Click Build Solution in the Build menu to compile the
solution Click Debug in the Start menu or press the F5 key
48
Simple Program: Displaying Text and an Image
Image property of the picture box.
Image property value (no image selected)
49
Simple Program: Displaying Text and an Image
Selecting an image for the picture box.
50
Simple Program: Displaying Text and an Image
Picture box after the image has been inserted.
Newly inserted image (after resizing the picture box)
51
Simple Program: Displaying Text and an Image
run mode, with the running application in the foreground.
Start button
End button
Run mode Design form
Design form (grid)
Running application
52
Simple Program: Displaying Text and an Image Terminating the program
Click the close button (x in the top right corner)
Or click the End button in the toolbar
Major Language Differences
Automatic memory management Garbage Collection No pointers
Everything inherits from System.Object Additional language constructs to aid in implementing
common patterns: Iterators – foreach and yield statements Data encapsulation – Properties Function pointers or Functors – delegates Observer Design Pattern – events Aspect-oriented programming – Attributes (loosely) Functional programming – LINQ and anonymous methods
Other Language Differences
Conditionals must evaluate to a BooleanNo pointers. Use the dot “.” to access both
namespaces and fields/methods.All fields are initialized by the CLR (zero for
value types, null for reference types).The switch statement can take bool’s ,
enum’s, integral types and strings.Expressions must be useful (no a==b;).
55
Simple Program// 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
59
Atomic Data
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)
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();
62
C#
Comments
Comments can be created using //…
Multi-lines comments use /* … */
Comments are ignored by the compiler
63
C#
Keywords
Words that cannot be used as variable or
class names
Have a specific unchangeable function
within the language
Example: class
Classes And Structs class CPoint { int x, y; ... }
struct SPoint { int x, y; ... }
CPoint cp = new CPoint(10, 20);SPoint sp = new SPoint(10, 20);
1010
2020spsp
cpcp
1010
2020
CPointCPoint
65
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 (@)
66
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
67
C# Statements
Anything in quotes (“) is considered a string
Every statement must end in a semicolon (;)
68
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.
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