Lecture 22: C#: “Sharp”, “Hash” or “Pound”? CS201j: Engineering Software University of Virginia Computer Science David Evans http://www.cs.virginia.edu/evans 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 26 November 2002 CS 201J Fall 2002 2 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 26 November 2002 CS 201J Fall 2002 3 26 November 2002 CS 201J Fall 2002 4 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) 26 November 2002 CS 201J Fall 2002 5 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…” 26 November 2002 CS 201J Fall 2002 6 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) 26 November 2002 CS 201J Fall 2002 7 26 November 2002 CS 201J Fall 2002 8 “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 26 November 2002 CS 201J Fall 2002 9 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 26 November 2002 CS 201J Fall 2002 10 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 26 November 2002 CS 201J Fall 2002 11 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? 26 November 2002 CS 201J Fall 2002 12 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. 26 November 2002 CS 201J Fall 2002 13 C# - Java • Java compiles to Java • C# compiles to Microsoft Intermediate Language byte codes (JVML) (MSIL) • Java VM runs JVML • Microsoft Common Language Runtime code (CLR) runs MSIL code • Java VM (bytecode • CLR verifies safety verifier) verifies safety properties of JVML code properties of MSIL • Designed around • Designed around .NET Internet 26 November 2002 CS 201J Fall 2002 14 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) 26 November 2002 CS 201J Fall 2002 15 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! 26 November 2002 CS 201J Fall 2002 16 Boxing and Unboxing • Value types need to be “boxed” before they can be used as subtypes of object: int i = 123; int i = 123; object box = i; object box = new int_Box(i); int j = (int) box; 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. 26 November 2002 CS 201J Fall 2002 17 Implicit Boxing and Unboxing Vector v; int i = 23; Implicit boxing to put i value in heap object v.add (i); int el = (int) v.elementAt (0); 26 November 2002 CS 201J Fall 2002 18 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! 26 November 2002 CS 201J Fall 2002 19 MyInt Class class MyInt { private int val; public MyInt (int value) { val = value; } public static MyInt operator++ (MyInt mi) { mi.val++; return mi; } You can overload operators (this is why mi++ works) } public override string ToString () { return val.ToString (); } You need the override keyword to indicate 26 November 2002 when a method is overridden. CS 201J Fall 2002 20 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); Calls object.ToString () string s = mi.ToString (); Calls MyInt.ToString () Console.WriteLine (s); class1.cs(10,38): warning CS0114: } ConsoleApplication1.MyInt 20 26 November 2002 '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. CS 201J Fall 2002 21 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 26 November 2002 CS 201J Fall 2002 22 C# Example struct MyInt { private int val; public MyInt (int value) { val = value; } public static MyInt operator++ (MyInt mi) { static void Main(string[] args) mi.val++; return mi; { } int i = 20; object o = i; public override string ToString () { MyInt mi = new MyInt (20); return val.ToString (); 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! 26 November 2002 CS 201J Fall 2002 23 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 → : • Exceptions implements → : • 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 26 November 2002 CS 201J Fall 2002 24 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); 26 November 2002 CS 201J Fall 2002 25 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. 26 November 2002 CS 201J Fall 2002 26 “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? 26 November 2002 CS 201J Fall 2002 27 CLU (Liskov et. al., 1975) 26 November 2002 CS 201J Fall 2002 28 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 26 November 2002 CS 201J Fall 2002 29 CLU Datatype Implementation set = cluster [t: type] is create, insert, elements rep = array[t] Datatype implementation can have type parameters! Can’t do this in Java or C# (in create = proc () returns (set) C++, templates provide similar functionality return up (rep$new ()) very awkwardly) end create insert = proc (s: set, el: t) rep$addh (down (s), el) end insert No this object, need to explicitly pass in set. Explict conversions between rep and abstract type (up and down) elements = iter (s: set) yields (t) for el: t in rep$elements (down (s)) do yield el Simple and elegant way to define iteration end abstractions. Java has nothing (enumerations), end elements C# has foreach for builtin arrays and ArrayList end set type, but you can’t define your own. 26 November 2002 CS 201J Fall 2002 30 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 26 November 2002 CS 201J Fall 2002 31 What is the “J” for? 26 November 2002 CS 201tJ Fall 2002 32 “Jeffersonian” 26 November 2002 CS 201tJ Fall 2002 33 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 26 November 2002 CS 201tJ Fall 2002 34 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 26 November 2002 CS 201tJ Fall 2002 35