0% found this document useful (0 votes)
18 views

C#: "Sharp", "Hash" or "Pound"?: David Evans

This document discusses the history and development of C# as a programming language. It provides background on Java's origins at Sun Microsystems in the early 1990s. It then discusses Microsoft's development of C# in the late 1990s as an attempt to create a language that offered the performance of C with the safety and ease of development of Java. The document presents several key differences between C# and Java, such as C# compiling to Microsoft's Common Language Runtime instead of a virtual machine like Java. It also discusses features of C# like value types, boxing and unboxing, and how classes can override methods.

Uploaded by

anuja
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

C#: "Sharp", "Hash" or "Pound"?: David Evans

This document discusses the history and development of C# as a programming language. It provides background on Java's origins at Sun Microsystems in the early 1990s. It then discusses Microsoft's development of C# in the late 1990s as an attempt to create a language that offered the performance of C with the safety and ease of development of Java. The document presents several key differences between C# and Java, such as C# compiling to Microsoft's Common Language Runtime instead of a virtual machine like Java. It also discusses features of C# like value types, boxing and unboxing, and how classes can override methods.

Uploaded by

anuja
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Lecture 22:

C#: “Sharp”,
“Hash” or
“Pound”?

CS201j: Engineering Software


University of Virginia David Evans
Computer Science 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 Java TM

• 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
byte codes (JVML) Intermediate Language
(MSIL)
• Java VM runs JVML • Microsoft Common
code Language Runtime
• Java VM (bytecode
(CLR) runs MSIL code
verifier) verifies safety • CLR 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;
Boxing makes a copy of Object box = new Integer (i);
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;

v.add (i); Implicit boxing to put i value in heap object

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
} when a method is overridden.

26 November 2002 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.ToString()' hides
inherited member 'object.ToString()'.
ConsoleApplication1.MyInt
To make the current member override that
20 implementation, add the override keyword.
Otherwise add the new keyword.
26 November 2002 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
struct MyInt
{
C# Example private int val;
public MyInt (int value) { val = value; }

static void Main(string[] args) public static MyInt operator++ (MyInt mi) {
{ 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 → : 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

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) No this object, need to explicitly pass in set.
rep$addh (down (s), el) Explict conversions between rep and
end insert abstract type (up and down)
elements = iter (s: set) yields (t)
for el: t in rep$elements (down (s)) do
yield el
end Simple and elegant way to define iteration
end elements abstractions. Java has nothing (enumerations),
end set C# has foreach for builtin arrays and ArrayList
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

You might also like