1 / 35

David Evans cs.virginia/evans

Lecture 22: C#: “Sharp”, “Hash” or “Pound”?. David Evans http://www.cs.virginia.edu/evans. CS201j: Engineering Software University of Virginia Computer Science. Menu. Db and C# CLU What does the “J” in CS201J really stand for?. Today’s notes: web only

tova
Télécharger la présentation

David Evans cs.virginia/evans

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 22: C#: “Sharp”, “Hash” or “Pound”? David Evans http://www.cs.virginia.edu/evans CS201j: Engineering Software University of Virginia Computer Science

  2. Menu • Db and C# • CLU • What does the “J” in CS201J really stand for? Today’s notes: web only Lots of links to Java history and C# info CS 201J Fall 2002

  3. Java History • 1991: Green Project starts, developing software for interactive TV boxes • 1992: Develop a language, “Oak” for programming them • Renamed “Java” (by Kim Polese) in a meeting in a coffee shop • March 1995: Posted on the Sun web site • May 1995: Sun announces Java, HotJava browser, Netscape licenses CS 201J Fall 2002

  4. CS 201J Fall 2002

  5. Microsoft and JavaTM • Dec 1995: Microsoft licenses Java • Microsoft replaces Sun’s JNI native interface with their own “improved”, incompatible version • Oct 1997: Sun sues Microsoft – breach of contract to provide “Java compatible” products • Microsoft countersues Sun for failing to deliver an implementation that passes Sun’s test suite and failing to provide public test cases • Jan 2001: Sun wins lawsuit (Microsoft pays $20M, accepts termination of Java license, and agrees not to us Java trademarks) CS 201J Fall 2002

  6. Exam Question 10: “…attempt to implement a new language that will offer the performance advantages of C with the safety and ease of development advantages of Java…” CS 201J Fall 2002

  7. C# C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. It will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++. C# Language Specification (p. 15 of 403) CS 201J Fall 2002

  8. CS 201J Fall 2002

  9. “C# aims to combine the high productivity of Visual Basic (Java) and the raw power of C++.”Why is this hard? • Garbage collection depends on: • Knowing which values are addresses • Knowing that objects without references cannot be reached • If your language allows direct manipulation of addresses these are impossible CS 201J Fall 2002

  10. Possible Solution • Require type safety • No unchecked conversions between types, no conversions between numeric and pointer types • Restrict what can be done with addresses: statically check that only in-object manipulations are permitted • Microsoft’s solution: • Give up! Let programmers make sections of code “unsafe” then they can CS 201J Fall 2002

  11. Unsafe in C# While practically every pointer type construct in C or C++ has a reference type counterpart in C#, there are nonetheless situations where access to pointer types becomes a necessity. For example, interfacing with the underlying operating system, …, or implementing a time-critical algorithm may not be possible or practical without access to pointers. To address this need, C# provides the ability to write unsafe code. In unsafe code it is possible to declare and operate on pointers, to perform conversions between pointers and integral types, to take the address of variables, and so forth. In a sense, writing unsafe code is much like writing C code within a C# program. Unsafe code is in fact a “safe” feature from the perspective of both developers and users. Unsafe code must be clearly marked with the modifier unsafe, so developers can’t possibly use unsafe features accidentally, and the execution engine works to ensure that unsafe code cannot be executed in an untrusted environment. C# Language Specification, Appendix B CS 201J Fall 2002

  12. Unsafe static unsafe void copy (byte[] src, byte [] dst, int count) { fixed (byte* pSrc = src, pDst = dst) { byte *ps = pSrc; byte *pd = pDst; for (int n = count; n != 0; n--) { *pd = *ps; pd++; ps++; } } } Within an unsafe block, we can manipulate pointers similarly C. What if stop-and-copy garbage collector runs while inside the loop? CS 201J Fall 2002

  13. Fixed static unsafe void copy (byte[] src, byte [] dst, int count) { fixed (byte* pSrc = src, pDst = dst) { byte *ps = pSrc; byte *pd = pDst; for (int n = count; n != 0; n--) { *pd = *ps; pd++; ps++; } } } Fixed pins the object where it is; within the fixed block, garbage collector may not move src or dst. C# compiler will disallow assignments to pointers without the fixed. CS 201J Fall 2002

  14. Java compiles to Java byte codes (JVML) Java VM runs JVML code Java VM (bytecode verifier) verifies safety properties of JVML code Designed around Internet C# compiles to Microsoft Intermediate Language (MSIL) Microsoft Common Language Runtime (CLR) runs MSIL code CLR verifies safety properties of MSIL Designed around .NET C# - Java CS 201J Fall 2002

  15. Types • In Java: • Primitive Types: int, char, etc. (on the stack) • Object Types: objects, arrays (on the heap) • In C#: • Value Types: int, char, struct, etc. (on the stack) • Reference Types: objects, arrays (on the heap) • All types are subtypes of object (including value types) CS 201J Fall 2002

  16. struct types • Programmers can define their own types that will be stored on the stack public struct Point { public int x, y; } Point points[1000]; In fact, the built-in primitive types (e.g., int) in C# are just struct types! CS 201J Fall 2002

  17. Boxing and Unboxing • Value types need to be “boxed” before they can be used as subtypes of object: int i = 123;object box = i; int j = (int) box; int i = 123;object box = new int_Box(i); int i = 123;Object box = new Integer (i); Boxing makes a copy of a value type on the heap. Cast “unboxes”, can fail run-time type check. CS 201J Fall 2002

  18. Implicit Boxing and Unboxing Vector v; int i = 23; v.add (i); int el = (int) v.elementAt (0); Implicit boxing to put i value in heap object CS 201J Fall 2002

  19. C# Example static void Main(string[] args) { int i = 20; object o = i; MyInt mi = new MyInt (20); MyInt mi2 = mi; i++; mi++; Console.WriteLine (“Values: " + i + " / " + o + " / " + mi + " / " + mi2); } Values: 21 / 20 / 21 / 21 int may be a subtype of object, but assignment means something different for objects an ints! CS 201J Fall 2002

  20. MyInt Class class MyInt { private int val; public MyInt (int value) { val = value; } public static MyInt operator++ (MyInt mi) { mi.val++; return mi; } public override string ToString () { return val.ToString (); } } You can overload operators (this is why mi++ works) You need the override keyword to indicate when a method is overridden. CS 201J Fall 2002

  21. Without the override class MyInt { private int val; public MyInt (int value) { val = value; } public static MyInt operator++ (MyInt mi) { mi.val++; return mi; } public string ToString () { return val.ToString (); } } static void Main(string[] args) { MyInt mi = new MyInt (20); Console.WriteLine (mi); string s = mi.ToString (); Console.WriteLine (s); } Calls object.ToString () Calls MyInt.ToString () class1.cs(10,38): warning CS0114: 'ConsoleApplication1.MyInt.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. ConsoleApplication1.MyInt 20 CS 201J Fall 2002

  22. Overriding • Java • Overriding is automatic: lots of confusion between overriding and overloading • e.g., public boolean equals (Cell c) • Methods declared with final cannot be overrode • C# • Methods declared with virtual can be overridden, must explicitly use override keyword in method header • Methods declared without virtual can be overriden but overriding method must use the new keyword in method header • Methods declared with sealed cannot be overriden CS 201J Fall 2002

  23. struct MyInt { private int val; public MyInt (int value) { val = value; } public static MyInt operator++ (MyInt mi) { mi.val++; return mi; } public override string ToString () { return val.ToString (); } } C# Example static void Main(string[] args) { int i = 20; object o = i; MyInt mi = new MyInt (20); MyInt mi2 = mi; i++; mi++; Console.WriteLine (“Values: " + i + " / " + o + " / " + mi + " / " + mi2); } Values: 21 / 20 / 21 / 20 MyInt is a struct instead of a class, so it is now stored on the stack, and assignment means copying! CS 201J Fall 2002

  24. Other Differences • synchronized→ lock • Meaning is identical (lock is a better name) • import→ using • Meaning slightly different (more like C++ namespaces than Java packages) • extends→ : implements→ : • Exceptions • C# can have catch without exception type (catches any exception like: catch (Exception e) … • C# has no throws clauses in declaration, and will compile code without catch clauses CS 201J Fall 2002

  25. Iteration Abstraction In Java: Vector v; //@v.elementType == \type(String) … for (Enumeration e = v.elements() ; e.hasMoreElements() ;) { System.out.println ((String) e.nextElement());} In C#: foreach (string s in namesList) Console.WriteLine(s); CS 201J Fall 2002

  26. Getters and Setters • In Java: • Need to define methods like getId (), getScore (), etc. by hand • In C#: public int Score { get { return score; } set { score = value; } } In client code: x.score = x.score + 1; x.setScore (x.getScore () + 1); Syntactic sugar for this in CLU. CS 201J Fall 2002

  27. “Sharp”, “Hash” or “Pound”? • Microsoft says: “pronounced C sharp” • But, it is hard to call any language with unsafe and fixed “sharp” • C# is a “hash” of C, Java and C++ • But, people might think they made a “hash” of it • The C# in a nutshell book weighs a few “pound”s • 856 pages, Java 4th edition = 992 pages, Stephen Hawking’s “Universe in a Nutshell” = 224 pages • But, it will be awkward to rename the second edition “Ckg in a Nutshell” • Db = a half-tone short of the successor to C? CS 201J Fall 2002

  28. CLU(Liskov et. al., 1975) CS 201J Fall 2002

  29. CLU • Language designed by Liskov’s group in the 1970s, focused on providing abstraction mechanisms • Your textbook was originally called “Abstraction and Specification in Program Development” and used CLU as the main language • CLU died due to lack of commercial compiler support • Only 2½ CLU programmers left CS 201J Fall 2002

  30. CLU Datatype Implementation set = cluster [t: type] is create, insert, elements rep = array[t] create = proc () returns (set) return up (rep$new ()) end create insert = proc (s: set, el: t) rep$addh (down (s), el) end insert elements = iter (s: set) yields (t) for el: t in rep$elements (down (s)) do yield el end end elements end set Datatype implementation can have type parameters! Can’t do this in Java or C# (in C++, templates provide similar functionality very awkwardly) No this object, need to explicitly pass in set. Explict conversions between rep and abstract type (up and down) Simple and elegant way to define iteration abstractions. Java has nothing (enumerations), C# has foreach for builtin arrays and ArrayList type, but you can’t define your own. CS 201J Fall 2002

  31. Good News / Bad News • Good News • You now know enough to list that you know Java, C, C# and CLU on your resume! • Bad News • No one is hiring CLU programmers • You shouldn’t want to work for anyone too easily impressed by you knowing the others Applicants must also have extensive knowledge of Unix, although they should have sufficiently good programming taste to not consider this an achievement. Hal Abelson, MIT job advertisement CS 201J Fall 2002

  32. What is the “J” for? CS 201tJ Fall 2002

  33. “Jeffersonian” CS 201tJ Fall 2002

  34. Snakes Tournament • Thursday’s class will meet in Olsson 001 (usual time): Open to anyone, bring your cheering supporters to intimidate your opponents • Qualification requirements: • Pass basic functionality tests • ESC/Java (don’t need to be warning-free to qualify, but must have annotated important, checkable invariants) • Tournaments: • Human driven snakes • Automatic snakes CS 201tJ Fall 2002

  35. Returning Exam 2 • You have a circled star on your exam: read the explanation on the exam comments carefully to interpret it! • Final cannot count against you, but it is more “optional” for some of you than others! • Final will be handed out Thursday, and due Tuesday, 10 December • A somewhat Jeffersonian essay question CS 201tJ Fall 2002

More Related