The Design and Evolution of C#
Anders Hejlsberg
Distinguished Engineer
Microsoft Corporation
Increasing Level of
Abstraction
C# Design Goals
Firmly planted in the { } language family
Component oriented
Unified and extensible type system
Robust and durable applications
Pragmatic design
Platform for future innovation
C# History
12/1998 – COOL project started
07/1999 – First internal ports to COOL
02/2000 – Named changed to C#
07/2000 – First public preview release
02/2002 – VS.NET 2002, C# 1.0 released
05/2003 – VS.NET 2003, C# 1.1 released
06/2004 – Beta 1 of VS 2005, C# 2.0
04/2005 – Beta 2 of VS 2005, C# 2.0
? ?/2005 – VS 2005, C# 2.0 release
Component Oriented
What defines a component?
Properties
Methods
Events
Attributes (meta-information)
C# has first class support
Not naming patterns, adapters, etc.
Not external files
Easy to build and consume components
Properties
A natural extension of fields
public class Button: Control
{
private string text;
}
public string Text {
get {
return text;
}
set {
text = value;
Repaint();
}
}
Button b = new Button();
b.Text = "OK";
string s = b.Text;
Events
Enable objects to provide notifications
public delegate void EventHandler(object sender, EventArgs e);
public class Button: Control
{
public event EventHandler Click;
void OnClick(EventArgs
Initialize() {
protected void
e) {
b = newe);
Button(…);
if (Click != Button
null) Click(this,
b.Click += ButtonClick;
}
}
}
void ButtonClick(object sender, EventArgs e) {
MessageBox.Show("You pressed the button");
}
Attributes
Extensible metadata
Add information to types and members
Traditional solutions
Keywords, magic comments, naming patterns,
external files
C# solution: Attributes
[Help("http://example.com/Widget.htm")]
public class Widget
{
[Help("http://example.com/Widget.htm", Topic = "Display")]
public void Display(string text) {…}
}
Unified Type System
C# has two categories of types
Value types (e.g. int)
Reference types (e.g. string)
Both categories are extensible
Value types – structs and enums
Reference types – classes, interfaces, delegates
i
s
123
int i = 123;
string s = "Hello world";
"Hello world"
Unified Type System
All types ultimately inherit from object
Any piece of data can be stored,
transported, and manipulated with no
extra work
object
Stream
MemoryStream
string
FileStream
int
double
Unified Type System
Boxing
Allocates box, copies value into box
Unboxing
Checks type, copies value out of box
Pay as you go
int i = 123;
object o = i;
int j = (int)o;
i
123
System.Int32
o
j
123
123
Unified Type System
Benefits of unification
Eliminates “wrapper classes”
Value types can implement interfaces
Collection classes work with all types
Lots of examples in .NET Framework
string s = string.Format("Your total was {0} on {1}", total, date);
Hashtable t = new Hashtable();
t.Add(0, "zero");
t.Add(1, "one");
t.Add(2, "two");
Robust and Durable
Garbage collection
No memory leaks and stray pointers
Exceptions
Error handling is 1st class and mandatory
Type-safety
No uninitialized variables, unsafe casts
Versioning
Pervasive versioning considerations in all
aspects of language design
Versioning
Overlooked in most languages
C++ and Java have versioning issues
Pervasive versioning considerations in C#
Virtual methods and overriding
Overload resolution
Explicit interface implementation
const vs. readonly fields
Defaults for accessibility and virtualness
Versioning
class Base
{
} public virtual void Foo() {
Console.WriteLine("Base.Foo");
}
}
// version 2
1
class Derived: Base
// version 2b
1
2a
{
new public
public
virtual
override
virtual
void
void
void
Foo()
Foo()
Foo()
{ { {
Console.WriteLine("Derived.Foo");
base.Foo();
} Console.WriteLine("Derived.Foo");
} }
}
Lessons From History
Separation of int and bool
Expression statements must do work
No case fall-through
if (x = 100) {…}
// Error
x == 100;
// Error
switch (number) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
Parameter Arrays
Variable-length argument lists
Type-safe, unlike C++
static void PrintValues(params object[] args) {
foreach (object x in args) {
…
}
PrintValues(1);
}
PrintValues(2, "plus", 3, "equals", 5);
PrintValues(1, 10, 100);
object[] temp = new object[3];
temp[0] = 1;
temp[1] = 10;
temp[2] = 100;
PrintValues(temp);
Foreach Statement
Iteration of arrays
public static void Main(string[] args) {
foreach (string s in args) Console.WriteLine(s);
}
Iteration of IEnumerable collections
ArrayList accounts = Bank.GetAccounts(…);
foreach (Account a in accounts) {
if (a.Balance < 0) Console.WriteLine(a.CustName);
}
Switch on String
Color ColorFromFruit(string name) {
switch(name.ToLower()) {
case "apple":
return Color.Red;
case "banana":
return Color.Yellow;
case "carrot":
return Color.Orange;
default:
throw new InvalidArgumentException();
}
}
Platform for Innovation
Standardized language specification
ECMA C#/CLI standards, December 2001
ISO C#/CLI standards, April 2003
JIS C# standard, March 2005
Standardization of 2.0 features ongoing
Several CLI and C# implementations
.NET Framework and Visual C#
SSCLI – Shared source on XP, FreeBSD, OS X
Mono – Open source on Linux
Visual Studio 2005 and C# 2.0
Generics
Anonymous methods
Nullable value types
Iterators
Partial types
…and many more
Generics
Why generics?
Type safety, performance, increased sharing
C# generics vs. Java generics
Exact run-time type information vs. erasure
Entire type system vs. only reference types
Invariant vs. wildcards
public class List<T> {…}
List<int> numbers = new List<int>();
List<Customer> customers = new List<Customer>();
Anonymous Methods
Also known as  functions
Permits code block in place of delegate
Delegate type automatically inferred
Closures are fully supported
List<Account> accounts = GetBankAccounts(…);
List<Account> overdrawn =
accounts.FindAll(delegate(Account a) { return a.Balance < 0; });
Visual C# 2005
Productivity
Developer productivity
Write code
Navigate code
Refactor code
Debug code
Team productivity
Source code control
Build code
Visualize code
Migrate code
Visual C# 2005
Future: Database Integration
Problem: Data != objects
O-R APIs are a step in the right direction
Rows are strongly typed, but queries are not
Asymmetric query facilities
Problem: Domain specific query languages
SQL for relational data
XPath, XSL/T, XQuery for XML
Query and set operations in C#
Unified syntax for local and remote data
Goal: True database integration in C#!
Resources
Visual C# 2005 Express Beta
http://msdn.microsoft.com/express/vcsharp
C# Language home page
http://msdn.microsoft.com/vcsharp/language
© 2003-2004 Microsoft Corporation. All rights reserved.
This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.