L02 1 - PowerPoint PPT Presentation

1 / 75
About This Presentation
Title:

L02 1

Description:

CS 3505. L02 - 1. Administrivia. Textbook: UML Distilled. We use part of it for the middle third of the class ... Great reference when you are trying to figure ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 76
Provided by: RobertR84
Category:

less

Transcript and Presenter's Notes

Title: L02 1


1
Administrivia
  • Textbook UML Distilled
  • We use part of it for the middle third of the
    class
  • Great reference when you are trying to figure out
    how to create the various diagrams
  • That stuff is available online by searching
  • No real assigned reading
  • MSDNAA and the software
  • HW1
  • Any questions?

2
HW 1 Game Loop
  • How do games work?
  • Sprites move across screen
  • Fast enough so you dont see flicker
  • Game loop controls this
  • It can either draw the sprites as fast as it can
  • Or it draws them on a set period of time (like
    once every 1/60th of a second)
  • Advantages and disadvantages of both
  • Mapping into a C form is tricky
  • Three solutions timer, thread, invalidate paint
    method
  • You can choose any of them

3
Contrast Timed vs. Infinite
  • If you want to move something from point a to
    point b, how do you do it in either one?
  • What else do you need to know?
  • What if you just have a velocity?
  • What is velocity defined as?
  • Understanding this is a key learning of this
    assignment

4
Review Last Lecture
  • What are the important concepts that we talked
    about last time?
  • .NET concept grew from Win32/COM
  • IL
  • CLR
  • Multiple languages
  • Always JIT

5
The C Language
  • Parts of this talk were stolen from
  • Mark Sapossnek, CS Dept, Metropolitan College,
    Boston University, CS 594 (in MSDNAA Curriculum
    Repository) (Introduction to C and Advanced C)
  • A Programmer's Introduction to C, Object ID 358
    in MSDNAA
  • The C Programming Language for Java Developers
    http//msdn.microsoft.com/vstudio/java/gettingstar
    ted/csharpforjava/

6
Design Goals of CThe Big Ideas
  • Component-orientation
  • Events, methods, properties
  • Everything is an object
  • Yes, this is different from Java and C and is
    POWERFUL
  • Robust and durable software
  • Preserving your investment
  • Easy to integrate with lots of stuff

7
Design Goals of C Component-Orientation
  • C is the first Component-Oriented language in
    the C/C family
  • What is a component?
  • An independent module of reuse and deployment
  • Coarser-grained than objects (objects are
    language-level constructs)
  • Includes multiple classes
  • Often language-independent
  • In general, component writer and user dont know
    each other, dont work for the same company, and
    dont use the same language

8
Design Goals of C Component-Orientation
  • Component concepts are first class
  • Properties, methods, events
  • Design-time and run-time attributes
  • Integrated documentation using XML
  • Enables one-stop programming
  • In some languages, header files or IDL are used
    to describe component interfaces
  • In C, this is built in
  • Thus, no .h/.cpp split
  • No forward declarations required
  • Thus no globals

9
Design Goals of C Everything is an Object
  • Traditional views
  • C, Java Primitive types are magic and do
    not interoperate with objects (but perform better
    no heap allocation)
  • Smalltalk, Lisp Primitive types are objects,
    but at some 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

10
Design Goals of C Robust and Durable Software
  • Garbage collection
  • No memory leaks and stray pointers
  • Exceptions
  • Type-safety
  • No uninitialized variables, no unsafe casts
  • Versioning
  • Avoid common errors
  • E.g. if (x y) ...
  • One-stop programming
  • Fewer moving parts
  • See version 3.0 features!!

11
Design Goals of C Preserving Your Investment
  • C Heritage
  • Namespaces, pointers (in unsafe code), unsigned
    types, etc.
  • Some changes, but no unnecessary sacrifices
  • Feels more like C than Java in terms of
    language, but feels more like Java in terms of
    environment
  • Interoperability
  • What software is increasingly about
  • C talks to XML, SOAP, COM, DLLs, and any .NET
    Framework language
  • Increased productivity
  • Short learning curve
  • Millions of lines of C code in .NET

12
Program Structure
  • Physical organization
  • Types are defined in files (each type in 1 or
    more files partial classes)
  • Partial classes!!
  • Files are compiled into modules
  • Modules are grouped into assemblies
  • Assemblies usually 1 to 1 with modules

13
Files, Preprocessor, Namespace
  • C style comments (// and / /
  • Files in C and Java
  • C header and cpp file, multiple classes per
    file allowed
  • Java one file with one class per file and file
    named same class
  • C
  • One file (.cs extension)
  • Any number of class definitions per file allowed
  • C has C preprocessor concept (define, etc.)
  • Java uses the package concept, C uses namespace
  • Allow multiple namespaces per file
  • Also have alias using foo namespace.namespace.c
    lass
  • C always uses . no more . or -gt or

C using ltnamespace hierarchygt.ltclass namegt
namespace ltnamespace namegt class Customer
...
JAVA package ltPackage namegt import ltpackage
hierarchygt.ltclass namegt class Customer
...
14
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"
15
Types Unified Type System
  • Value types
  • Primitives int i float x
  • Enums enum State Off, On
  • Structs struct Point int x,y
  • Unsigned ints are included for writing systems
    code (not in Java)
  • Reference types
  • Root object
  • String string
  • Classes class Foo Bar, IFoo ...
  • Interfaces interface IFoo IBar ...
  • Arrays string a new string10
  • Delegates delegate void Empty()

16
Types Unified Type System
17
Types Unified Type System
  • Benefits of value types
  • No heap allocation, less GC pressure
  • More efficient use of memory
  • Less reference indirection
  • Unified type system
  • No primitive/object dichotomy
  • THIS IS A BIG DEAL!!!!

18
TypesConversions
int x 123456 long y x // implicit short z
(short)x // explicit double d
1.2345678901234 float f (float)d //
explicit long l (long)d // explicit
  • Implicit conversions
  • Occur automatically
  • Guaranteed to succeed
  • No information (precision) loss
  • Explicit conversions
  • Require a cast
  • May not succeed
  • Information (precision) might be lost
  • Both implicit and explicit conversions can be
    user-defined

19
TypesUnified Type System
  • Everything is an object
  • All types ultimately inherit from object
  • Any piece of data can be stored, transported, and
    manipulated with no extra work

20
TypesUnified Type System
  • Polymorphism
  • The ability to perform an operation on an object
    without knowing the precise type of the object
  • Notice use of primitive types too!! (Java added
    in 1.5)

void Poly(object o) Console.WriteLine(o.ToStri
ng())
Poly(42) Poly(abcd) Poly(12.345678901234m) Po
ly(new Point(23,45))
21
TypesUnified Type System
  • Question How can we treat value and reference
    types polymorphically?
  • How does an int (value type) get converted into
    an object (reference type)?
  • Answer Boxing!
  • Boxing take something and wrap it up and put it
    into a Box!!! (objectification ?)
  • A key innovation of C
  • Only value types get boxed
  • Reference types do not get boxed

22
TypesUnified Type System
  • Boxing
  • Copies a value type into a reference type
    (object)
  • Each value type has corresponding hidden
    reference type
  • Note that a reference-type copy is made of the
    value type
  • Value types are never aliased
  • Value type is converted implicitly to object, a
    reference type
  • Essentially an up cast
  • So you can do things like toString on an int

23
TypesUnified Type System
  • Unboxing
  • Inverse operation of boxing
  • Copies the value out of the box
  • Copies from reference type to value type
  • Requires an explicit conversion
  • May not succeed (like all explicit conversions)
  • Essentially a down cast

24
TypesUnified Type System
  • Boxing and unboxing

123
i
int i 123 object o i int j (int)o
System.Int32
o
123
123
j
25
TypesUnified Type System
  • Benefits of boxing
  • Enables polymorphism across all types
  • Collection classes work with all types
  • Oh, yeah, this is HUGELY cool!!!
  • Eliminates need for wrapper classes
  • Disadvantages of boxing
  • Some performance cost doing the conversion

26
Classes
  • The class concept is pretty much the same as for
    Java and C and C
  • Some syntactic differences
  • Like how you specify inheritance
  • C permits multiple inheritance
  • C has destructors (Java doesnt)
  • Other differences we will see as we go along

27
Class Access Control
  • public visible to all
  • protected visible only from derived classes
  • private visible only within the given class
    (default, where in Java default is internal)
  • internal visible only within the same assembly
  • protected internal visible only to the current
    assembly or types derived from the containing
    class
  • sealed - cant be inherited (like final in Java)
    structs are implicitly sealed
  • const like C (compile time)
  • read-only like const, but runtime, set in
    constructor

28
Class Inheritance
  • Use to indicate inheritance (like extends in
    Java)
  • Just like C
  • Constructors can invoke base constructor by
    mentioning name as in C
  • public child (int x, int y) base(x, y)
  • Casting up and down like C
  • Use virtual keyword to indicate virtual functions
  • Abstract class concept
  • Using abstract keyword

29
Interfaces in Java 1.4
interface IA void g ()
interface IB extends IA void f ()
interface IC extends IA void f ()
class X implements IB, IC void ()
System.out.println ("g") void ()
System.out.println ("f")
g
f
ERROR This will not compile in JAVA 1.4 and
before
30
Interfaces in Java 1.5
interface IA void g ()
interface IB extends IA void f ()
interface IC extends IA void f ()
class X implements IB, IC void ()
System.out.println ("g") void ()
System.out.println ("f")
g
f
This will compile in JAVA 1.5! Notice, only one
f()!
31
Interfaces in C
class Test public static void Main () X
x new X () ((IA)x).g() ((IC)x).f()
((IB)x).f()
interface IA void g ()
interface IB IA void f ()
interface IC IA void f ()
class X IB, IC void ()
Console.WriteLine ("IA.g") void ()
Console.WriteLine ("IC.f") void ()
Console.WriteLine ("IB.f")
IA.g
IC.f
IB.f
32
Structs
  • Similar to classes, but
  • User-defined value type
  • Always inherits from object
  • High performance
  • Stack allocated
  • Ideal for lightweight objects
  • int, float, double, etc., are all structs
  • User-defined primitive types
  • Complex, point, rectangle, color, rational
  • Multiple interface inheritance
  • Same members as class
  • Member access
  • public, internal, private
  • Instantiated with new operator
  • Structs are final cant inherit from them

33
Allocation Structs vs. Classes
struct SPoint int x, y ... class CPoint
int x, y ... SPoint sp new SPoint(10,
20) CPoint cp new CPoint(10, 20)
10
sp
20
cp
CPoint
10
20
34
Classes and Structs - Similarities
  • Both are user-defined types
  • Both can implement multiple interfaces
  • Both can contain
  • Data
  • Fields, constants, events, arrays
  • Functions
  • Methods, properties, indexers, operators,
    constructors
  • Type definitions
  • Classes, structs, enums, interfaces, delegates

35
Classes and Structs - Differences
36
C Structs vs. C Structs
  • Very different from C struct

37
Class Example
public class Car Vehicle public enum Make
GM, Honda, BMW Make make string vid
Point location Car(Make m, string vid Point
loc) this.make m this.vid vid
this.location loc public void Drive()
Console.WriteLine(vroom)
Car c new Car(Car.Make.BMW,
JF3559QT98, new Point(3,7)) c.Drive(
)
38
Struct Example
public struct Point int x, y public
Point(int x, int y) this.x x this.y
y public int X get return x set
x value public int Y get return y
set y value
These are properties which well describe later.
Point p new Point(2,5) p.X 100 int px
p.X // px 102
39
Enums
enum Suit Clubs 0, Diamonds 1,
Hearts, Spades Suit s
Suit.Clubs Console.WriteLine (s) //-gt
Clubs Console.WriteLine((int)s) //-gt 0 Suit s2
Suit.Spades Console.WriteLine((int)s2) //-gt3
  • Enums are first class
  • Enums are typesafe
  • Values are optional

40
Most Operators SimilarCheck out is
using System public class ShowTypes public
static void Main(string args) CheckType
(5) CheckType (10f) CheckType
("Hello") private static void CheckType
(object obj) if (obj is int)
Console.WriteLine("Integer parameter")
else if (obj is float)
Console.WriteLine("Float parameter") else
if (obj is string) Console.WriteLine("Str
ing parameter")
41
StatementsOverview
  • High C fidelity
  • if, while, do require bool condition
  • no if (x1) error
  • goto cant jump into blocks
  • switch statement
  • No fall-through is allowed you must use break
  • foreach statement
  • Go through arrays or collections
  • Expression statements must do work

void Foo() i 1 // error
42
StatementsVariables
  • Variables must be assigned a value before they
    can be used
  • Explicitly or automatically
  • Called definite assignment
  • Automatic assignment occurs for static fields,
    class instance fields and array elements

void Foo() string s Console.WriteLine(s)
// Error
43
StatementsVariables and Constants
  • Within the scope of a variable or constant it is
    an error to declare another variable or constant
    with the same name

int x int x // Error cant hide
variable x
44
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)
  • args0 param1, args1 param2 (in C
    args0 is program.exe name)

45
Passing Arguments
  • Java
  • Primitives by value Objects by ref
  • C
  • By value with copy constructors for objects
    Reference by specification
  • C
  • Primitives by value Objects by ref Value can be
    by ref by saying ref
  • out just like ref except initial value
    ignored, and MUST be assigned
  • using System
  • public class RefClass
  • public static void Main(string args)
  • int total 20
  • Console.WriteLine("Original value of 'total'
    0", total)
  • // Call the Add method
  • Add (10, ref total)
  • Console.WriteLine("Value after Add() call
    0", total)
  • public static void Add (int i, ref int result)
  • result i

46
Properties
  • Formalized getter/setter model of Java
  • public class Animal
  • private string name
  • public string Species
  • get return name
  • set name value // Notice magic variable
    value
  • Animal animal new Animal()
  • animal.Species "Lion" // Set the property
  • str animal.Species // Get the property value
    string
  • Compiles to get_Species/set_Species for languages
    that dont have properties yet

47
Indexers
Does not HAVE to be an int, but often that is
what you want.
  • Give array like behaviour to any class
  • Define property on this and add square brackets
  • public class Skyscraper
  • Story stories
  • public Story this int index
  • get return storiesindex
  • set if (value!null)
  • storiesindex value
  • SkyScraper searsTower new SkyScraper()
  • searsTower155 new Story(Observation Deck)
  • searsTower0 new Story(Entrance)

48
Operator Overloading
  • Just like in C
  • public static complex operator(complex lhs,
    complex rhs)

49
Exceptions
C Compiler forces increasing generality when
using multiple exceptions (Java does not)
try throw new FooException(Oops!) catch
(FooException e) Handle exception
catch Catch all other exceptions
finally clean up, even if no exception
occurred
50
Delegates
  • C and others have function pointers
  • Java does not
  • C does with the delegate
  • A delegate is a reference type that defines a
    method signature
  • Method signature is both return type and argument
    types
  • When instantiated, a delegate holds one or more
    methods
  • Essentially an object-oriented function pointer

delegate void myDelegate(int a, int b)
myDelegate operation new myDelegate(Add)
operation new myDelegate(Multiply)
operation(1,2)
Will actually call both the Add AND the Multiply
methods
51
DelegatesMulticast Delegates
  • A delegate can hold and invoke multiple methods
  • Multicast delegates must contain only methods
    that return void, else there is a run-time
    exception
  • Each delegate has an invocation list
  • Methods are invoked sequentially, in the order
    added
  • The and - operators are used to add and
    remove delegates, respectively
  • and - operators are thread-safe

52
DelegatesMulticast Delegates
delegate void SomeEvent(int x, int y) static
void Foo1(int x, int y) Console.WriteLine("Foo
1") static void Foo2(int x, int y)
Console.WriteLine("Foo2") public static void
Main() SomeEvent func new SomeEvent(Foo1)
func new SomeEvent(Foo2) func(1,2)
// Foo1 and Foo2 are called func - new
SomeEvent(Foo1) func(2,3) // Only
Foo2 is called
53
EventsOverview
  • Event handling is a style of programming where
    one object notifies another that something of
    interest has occurred
  • A publish-subscribe programming model
  • Events allow you to tie your own code into the
    functioning of an independently created component
  • Events are a type of callback mechanism

54
EventsOverview
  • Events are well suited for user-interfaces
  • The user does something (clicks a button, moves a
    mouse, changes a value, etc.) and the program
    reacts in response
  • In many systems, the event loop comes with the
    user interface
  • Many other uses, e.g.
  • Time-based events
  • Asynchronous operation completed
  • Email message has arrived
  • A web session has begun

55
EventsOverview
  • C has native support for events
  • One of the first real languages to do this
  • Based upon delegates (COOL IDEA)
  • An event is essentially a field holding a
    delegate
  • However, public users of the class can only
    register delegates
  • They can only call and -
  • They cant invoke the events delegate
  • Multicast delegates allow multiple objects to
    register with the same event

56
EventsExample Component-Side
  • Define the event signature as a delegate
  • Define the event and firing logic

public delegate void EventHandler(object sender,
EventArgs e)
public class Button public event EventHandler
Click protected void OnClick(EventArgs e)
// This is called when button is clicked if
(Click ! null) Click(this, e)
57
EventsExample User-Side
  • Define and register an event handler

public class MyForm Form Button okButton
static void OkClicked(object sender, EventArgs e)
ShowMessage("You pressed the OK button")
public MyForm() okButton new
Button(...) okButton.Caption "OK"
okButton.Click new EventHandler(OkClicked)

58
Create New Thread
AABBBBAAAABBBBBBAAAAAABBBABABBBAABABBBABBAAAABABAB
ABABBBABBBABBBABBBBBBBABBABBBBBAAAAAAABBBABBABBBAB
BBBABABABBBABABABBABABBBAABAAABABBBABBBB
using Systemusing System.Threadingclass Test
static void printA () while (true)
Console.Write("A") static void printB ()
while (true) Console.Write("B")
public static void Main () Thread a new
Thread(new ThreadStart(printA)) Thread b
new Thread(new ThreadStart(printB))
a.Start() b.Start()
59
Locks and Critical Sections
lock(e) .
public class CheckingAccount decimal
balance public void Deposit(decimal amount)
lock (this) balance amount
public void Withdraw(decimal amount)
lock (this) balance - amount
60
XML CommentsOverview
  • Java has javadoc
  • C lets you embed XML comments that document
    types, members, parameters, etc.
  • Denoted with triple slash ///
  • XML document is generated when code is compiled
    with /doc argument
  • Comes with predefined XML schema, but you can add
    your own tags too
  • Some are verified, e.g. parameters, exceptions,
    types

61
XML CommentsOverview
62
XML CommentsOverview
class XmlElement /// ltsummarygt ///
Returns the attribute with the given name and
/// namespacelt/summarygt /// ltparam
name"name"gt /// The name of the
attributelt/paramgt /// ltparam name"ns"gt ///
The namespace of the attribute, or null if
/// the attribute has no namespacelt/paramgt
/// ltreturngt /// The attribute value, or
null if the attribute /// does not
existlt/returngt /// ltseealso cref"GetAttr(strin
g)"/gt /// public string GetAttr(string
name, string ns) ...
63
AttributesOverview
  • Its often necessary to associate information
    (metadata) with types and members, e.g.
  • Documentation URL for a class
  • Transaction context for a method
  • XML persistence mapping
  • Attributes allow you to decorate a code element
    (assembly, module, type, member, return value and
    parameter) with additional information

64
AttributesOverview
HelpUrl(http//SomeUrl/APIDocs/SomeClass) clas
s SomeClass Obsolete(Use SomeNewMethod
instead) public void SomeOldMethod()
... public string Test(SomeAttr()
string param1) ...
65
AttributesOverview
  • Attributes are superior to the alternatives
  • Modifying the source language
  • Using external files, e.g., .IDL, .DEF
  • Attributes are extensible
  • Attributes allow to you add information not
    supported by C itself
  • Not limited to predefined information
  • Built into the .NET Framework, so they work
    across all .NET languages
  • Stored in assembly metadata

66
AttributesOverview
  • Some predefined .NET Framework attributes

67
AttributesOverview
  • Attributes can be
  • Attached to types and members
  • Examined at run-time using reflection
  • Completely extensible
  • Simply a class that inherits from
    System.Attribute
  • Type-safe
  • Arguments checked at compile-time
  • Extensive use in .NET Framework
  • XML, Web Services, security, serialization,
    component model, COM and P/Invoke interop, code
    configuration

68
AttributesQuerying Attributes
HelpUrl("http//SomeUrl/MyClass") class Class1
HelpUrl("http//SomeUrl/MyClass"),
HelpUrl("http//SomeUrl/MyClass, Tagctor)
class Class2
Type type typeof(MyClass) foreach (object
attr in type.GetCustomAttributes() ) if (
attr is HelpUrlAttribute )
HelpUrlAttribute ha (HelpUrlAttribute) attr
myBrowser.Navigate( ha.Url )
69
Unsafe CodeOverview
  • Developers sometime need total control
  • Performance extremes
  • Dealing with existing binary structures
  • Existing code
  • Advanced COM support, DLL import
  • C allows you to mark code as unsafe, allowing
  • Pointer types, pointer arithmetic
  • -gt, operators
  • Unsafe casts
  • No garbage collection

70
Unsafe CodeOverview
  • Lets you embed native C/C code
  • Basically inline C
  • Must ensure the GC doesnt move your data
  • Use fixed statement to pin data
  • Use stackalloc operator so memory is allocated on
    stack, and need not be pinned

unsafe void Foo() char buf stackalloc
char256 for (char p buf p lt buf 256
p) p 0 ...
71
Unsafe CodeOverview
class FileStream Stream int handle
public unsafe int Read(byte buffer, int index,
int count) int n
0 fixed (byte p buffer)
ReadFile(handle, p index, count, n, null)
return n dllimport("kernel32",
SetLastErrortrue) static extern unsafe bool
ReadFile(int hFile, void lpBuffer, int
nBytesToRead, int nBytesRead, Overlapped
lpOverlapped)
72
Unsafe CodeC and Pointers
  • Power comes at a price!
  • Unsafe means unverifiable code
  • Stricter security requirements
  • Before the code can run
  • Downloading code

73
Performance
  • Lots of performance studies
  • One that seems competent is (but this is a couple
    years old)
  • http//www.tommti-systems.de/go.html?http//www.to
    mmti-systems.de/main-Dateien/reviews/languages/ben
    chmarks.html
  • Some numbers
  • Maximum memory usage
  • Java - 163 MB
  • C - 111 MB
  • Cpp - 98 MB
  • Performance summary (lots of tests)
  • Cpp is the fastest, except the STL "hashmaps" (11
    wins against C)
  • C is quit fast (problems with exception
    handling, matrix multiply and nested loops)
  • Java is slower, but hash maps are very fast and
    the exception handling is also very strong.
  • C 11 wins against C
  • Java 5 wins against C
  • C 9 wins against Java
  • C 2 wins against C

74
Summary
  • C has lots of nice features
  • Clearly C was built after C and Java and fixes
    problems and issues
  • C language feels more like C
  • C environment is more Java like
  • Easy to learn language
  • Work will come in learning the libraries (.Net
    Framework and XNA libraries)
  • Next time What about C 2.0?
  • Generics
  • Partial classes
  • Anonymous delegates

75
Discussion Tomorrow
  • Do the discussion tomorrow
  • Next homework will be building a more capable
    game than the cat/mouse one that you will build
    tomorrow
  • Note if you have any cats, bring a small
    GIF/JPG/BMP image with you to the discussion ?
    It will be fun!!!
Write a Comment
User Comments (0)
About PowerShow.com