Introduction to C# Introduction to C#
Anders Anders HejlsbergHejlsberg
Distinguished EngineerDistinguished Engineer
Developer DivisionDeveloper Division
Microsoft CorporationMicrosoft Corporation
C# C# –– The Big IdeasThe Big Ideas
The first component oriented The first component oriented
language in the C/C++ familylanguage in the C/C++ family
Everything really is an objectEverything really is an object
Next generation robust and Next generation robust and
durable softwaredurable software
Preservation of investmentPreservation of investment
C# C# –– The Big IdeasThe Big Ideas
A component oriented languageA component oriented language
C# is the first “component oriented” C# is the first “component oriented”
language in the C/C++ familylanguage in the C/C++ family
Component concepts are first class:Component concepts are first class:
Properties, methods, eventsProperties, methods, events
DesignDesign--time and runtime and run--time attributestime attributes
Integrated documentation using XMLIntegrated documentation using XML
Enables oneEnables one--stop programmingstop programming
No header files, IDL, etc.No header files, IDL, etc.
Can be embedded in web pagesCan be embedded in web pages
C# C# –– The Big IdeasThe Big Ideas
Everything really is an objectEverything really is an object
Traditional viewsTraditional views
C++, Java: Primitive types are “magic” and do C++, Java: Primitive types are “magic” and do
not interoperate with objectsnot interoperate with objects
Smalltalk, Lisp: Primitive types are objects, but Smalltalk, Lisp: Primitive types are objects, but
at great performance costat great performance cost
C# unifies with no performance costC# unifies with no performance cost
Deep simplicity throughout systemDeep simplicity throughout system
Improved extensibility and reusabilityImproved extensibility and reusability
New primitive types: Decimal, SQL…New primitive types: Decimal, SQL…
Collections, etc., work for Collections, etc., work for all all typestypes
C# C# –– The Big IdeasThe Big Ideas
Robust and durable softwareRobust and durable software
Garbage collectionGarbage collection
No memory leaks and stray pointersNo memory leaks and stray pointers
ExceptionsExceptions
Error handling is not an afterthoughtError handling is not an afterthought
TypeType--safetysafety
No No uninitializeduninitialized variables, unsafe castsvariables, unsafe casts
VersioningVersioning
Pervasive versioning considerations in Pervasive versioning considerations in
all aspects of language designall aspects of language design
C# C# –– The Big IdeasThe Big Ideas
Preservation of InvestmentPreservation of Investment
C++ heritageC++ heritage
Namespaces, Namespaces, enumsenums, unsigned types, pointers , unsigned types, pointers
(in unsafe code), etc.(in unsafe code), etc.
No unnecessary sacrificesNo unnecessary sacrifices
InteroperabilityInteroperability
What software is increasingly aboutWhat software is increasingly about
MS C# implementation talks to XML, SOAP, MS C# implementation talks to XML, SOAP,
COM, DLLs, and any .NET languageCOM, DLLs, and any .NET language
Millions of lines of C# code in .NETMillions of lines of C# code in .NET
Short learning curveShort learning curve
Increased productivityIncreased productivity
Hello WorldHello World
using System;using System;
class Helloclass Hello
{{
static void Main() {static void Main() {
Console.Console.WriteLineWriteLine("Hello world");("Hello world");
}}
}}
C# Program StructureC# Program Structure
NamespacesNamespaces
Contain types and other namespacesContain types and other namespaces
Type declarationsType declarations
Classes, Classes, structsstructs, interfaces, , interfaces, enumsenums, ,
and delegatesand delegates
MembersMembers
Constants, fields, methods, properties, indexers, Constants, fields, methods, properties, indexers,
events, operators, constructors, destructorsevents, operators, constructors, destructors
OrganizationOrganization
No header files, code written “inNo header files, code written “in--line”line”
No declaration order dependenceNo declaration order dependence
C# Program StructureC# Program Structure
using System;using System;
namespace System.Collectionsnamespace System.Collections
{{
public class Stackpublic class Stack
{{
Entry top;Entry top;
public void Push(object data) {public void Push(object data) {
top = new Entry(top, data);top = new Entry(top, data);
}}
public object Pop() {public object Pop() {
if (top == null) throw new if (top == null) throw new InvalidOperationExceptionInvalidOperationException();();
object result = top.data;object result = top.data;
top = top.next;top = top.next;
return result;return result;
}}
}}
}}
Type SystemType System
Value typesValue types
Directly contain dataDirectly contain data
Cannot be nullCannot be null
Reference typesReference types
Contain references to objectsContain references to objects
May be nullMay be null
intint i = 123;i = 123;
string s = "Hello world";string s = "Hello world";
ii 123123
ss "Hello world""Hello world"
Type SystemType System
Value typesValue types
PrimitivesPrimitives intint i;i;
EnumsEnums enumenum State { Off, On }State { Off, On }
StructsStructs structstruct Point {Point { intint x, y; }x, y; }
Reference typesReference types
ClassesClasses class Foo: Bar,class Foo: Bar, IFooIFoo {...}{...}
InterfacesInterfaces interface interface IFooIFoo:: IBarIBar {...}{...}
ArraysArrays string[] a = new string[10];string[] a = new string[10];
DelegatesDelegates delegate void Empty();delegate void Empty();
Predefined TypesPredefined Types
C# predefined typesC# predefined types
ReferenceReference object, stringobject, string
SignedSigned sbytesbyte, short,, short, intint, long, long
Unsigned Unsigned byte,byte, ushortushort,, uintuint, , ulongulong
CharacterCharacter charchar
FloatingFloating--pointpoint float, double, decimalfloat, double, decimal
LogicalLogical boolbool
Predefined types are simply aliases Predefined types are simply aliases
for systemfor system--provided typesprovided types
For example,For example, intint == System.Int32== System.Int32
ClassesClasses
Single inheritanceSingle inheritance
Multiple interface implementationMultiple interface implementation
Class membersClass members
Constants, fields, methods, properties, Constants, fields, methods, properties,
indexers, events, operators, indexers, events, operators,
constructors, destructorsconstructors, destructors
Static and instance membersStatic and instance members
Nested typesNested types
Member accessMember access
public, protected, internal, privatepublic, protected, internal, private
StructsStructs
Like classes, exceptLike classes, except
Stored inStored in--line, not heap allocatedline, not heap allocated
Assignment copies data, not referenceAssignment copies data, not reference
No inheritanceNo inheritance
Ideal for light weight objectsIdeal for light weight objects
Complex, point, rectangle, colorComplex, point, rectangle, color
intint, float, double, etc., are all , float, double, etc., are all structsstructs
BenefitsBenefits
No heap allocation, less GC pressureNo heap allocation, less GC pressure
More efficient use of memoryMore efficient use of memory
Classes And Classes And StructsStructs
class class CPointCPoint {{ intint x, y; ... }x, y; ... }
structstruct SPoint SPoint { { int int x, y; ... }x, y; ... }
CPointCPoint cp = new cp = new CPointCPoint(10, 20);(10, 20);
SPointSPoint sp = new sp = new SPointSPoint(10, 20);(10, 20);
1010
spsp
2020
cpcp
1010
2020
CPointCPoint
InterfacesInterfaces
Multiple inheritanceMultiple inheritance
Can contain methods, properties, Can contain methods, properties,
indexers, and eventsindexers, and events
Private interface implementationsPrivate interface implementations
interface interface IDataBoundIDataBound
{{
void Bind(void Bind(IDataBinder IDataBinder binder);binder);
}}
class class EditBoxEditBox: Control, : Control, IDataBoundIDataBound
{{
void void IDataBoundIDataBound.Bind(.Bind(IDataBinder IDataBinder binder) {...}binder) {...}
}}
EnumsEnums
Strongly typedStrongly typed
No implicit conversions to/from No implicit conversions to/from intint
Operators: +, Operators: +, --, ++, , ++, ----, &, |, ^, ~, &, |, ^, ~
Can specify underlying typeCan specify underlying type
Byte, short, Byte, short, intint, long, long
enum enum Color: byteColor: byte
{{
Red = 1,Red = 1,
Green = 2,Green = 2,
Blue = 4,Blue = 4,
Black = 0,Black = 0,
White = Red | Green | Blue,White = Red | Green | Blue,
}}
DelegatesDelegates
Object oriented function pointersObject oriented function pointers
Multiple receiversMultiple receivers
Each delegate has an invocation listEach delegate has an invocation list
ThreadThread--safe + and safe + and -- operationsoperations
Foundation for eventsFoundation for events
delegate voiddelegate void MouseEventMouseEvent((intint x,x, intint y);y);
delegate doubledelegate double FuncFunc(double x);(double x);
Func funcFunc func = new= new FuncFunc(Math.Sin);(Math.Sin);
double x =double x = funcfunc(1.0);(1.0);
Unified Type SystemUnified Type System
Everything is an objectEverything is an object
All types ultimately inherit from objectAll types ultimately inherit from object
Any piece of data can be stored, Any piece of data can be stored,
transported, and manipulated with no transported, and manipulated with no
extra workextra work
StreamStream
MemoryStreamMemoryStream FileStreamFileStream
HashtableHashtable doubledoubleintint
objectobject
Unified Type SystemUnified Type System
BoxingBoxing
Allocates box, copies value into itAllocates box, copies value into it
UnboxingUnboxing
Checks type of box, copies value outChecks type of box, copies value out
intint i = 123;i = 123;
object o = i;object o = i;
intint j = (j = (intint)o;)o;
123123i
System.Int32System.Int32o
123123
123123j
Unified Type SystemUnified Type System
BenefitsBenefits
Eliminates “wrapper classes”Eliminates “wrapper classes”
Collection classes work with all typesCollection classes work with all types
Replaces OLE Automation's VariantReplaces OLE Automation's Variant
Lots of examples in .NET FrameworkLots of examples in .NET Framework
string s = string.Format(string s = string.Format(
"Your total was {0} on {1}", total, date);"Your total was {0} on {1}", total, date);
HashtableHashtable t = newt = new HashtableHashtable();();
t.Add(0, "zero");t.Add(0, "zero");
t.Add(1, "one");t.Add(1, "one");
t.Add(2, "two");t.Add(2, "two");
Component DevelopmentComponent Development
What defines a component?What defines a component?
Properties, methods, eventsProperties, methods, events
Integrated help and documentationIntegrated help and documentation
DesignDesign--time informationtime information
C# has first class supportC# has first class support
Not naming patterns, adapters, etc.Not naming patterns, adapters, etc.
Not external filesNot external files
Components are easy to build Components are easy to build
and consumeand consume
PropertiesProperties
Properties are “smart fields”Properties are “smart fields”
Natural syntax, Natural syntax, accessorsaccessors, , inlininginlining
public class Button: Controlpublic class Button: Control
{{
private string caption;private string caption;
public string Caption {public string Caption {
get {get {
return caption;return caption;
}}
set {set {
caption = value;caption = value;
Repaint();Repaint();
}}
}}
}}
Button b = new Button();Button b = new Button();
b.Caption = "OK";b.Caption = "OK";
String s = b.Caption;String s = b.Caption;
IndexersIndexers
Indexers are “smart arrays”Indexers are “smart arrays”
Can be overloadedCan be overloaded
public classpublic class ListBoxListBox: Control: Control
{{
private string[] items;private string[] items;
public string this[public string this[intint index] {index] {
get {get {
return items[index];return items[index];
}}
set {set {
items[index] = value;items[index] = value;
Repaint();Repaint();
}}
}}
}}
ListBox listBoxListBox listBox = new = new ListBoxListBox();();
listBoxlistBox[0] = "hello";[0] = "hello";
Console.Console.WriteLineWriteLine((listBoxlistBox[0]);[0]);
Events Events
SourcingSourcing
Define the event signatureDefine the event signature
Define the event and firing logicDefine the event and firing logic
public delegate void public delegate void EventHandlerEventHandler(object sender, (object sender, EventArgsEventArgs e);e);
public class Buttonpublic class Button
{{
public eventpublic event EventHandlerEventHandler Click;Click;
protected voidprotected void OnClickOnClick((EventArgsEventArgs e) {e) {
if (Click != null) Click(this, e);if (Click != null) Click(this, e);
}}
}}
Events Events
HandlingHandling
Define and register event handlerDefine and register event handler
public class public class MyFormMyForm: Form: Form
{{
Button Button okButtonokButton;;
public public MyFormMyForm() {() {
okButton okButton = new Button(...);= new Button(...);
okButtonokButton.Caption = "OK";.Caption = "OK";
okButtonokButton.Click += new .Click += new EventHandlerEventHandler((OkButtonClickOkButtonClick););
}}
void void OkButtonClickOkButtonClick(object sender, (object sender, EventArgs EventArgs e) {e) {
ShowMessageShowMessage("You pressed the OK button");("You pressed the OK button");
}}
}}
AttributesAttributes
How do you associate information How do you associate information
with types and members?with types and members?
Documentation URL for a classDocumentation URL for a class
Transaction context for a methodTransaction context for a method
XML persistence mappingXML persistence mapping
Traditional solutionsTraditional solutions
Add keywords or Add keywords or pragmaspragmas to languageto language
Use external files, e.g., .IDL, .DEFUse external files, e.g., .IDL, .DEF
C# solution: AttributesC# solution: Attributes
AttributesAttributes
public class public class OrderProcessorOrderProcessor
{{
[[WebMethodWebMethod]]
public void public void SubmitOrderSubmitOrder((PurchaseOrder PurchaseOrder order) {...}order) {...}
}}
[[XmlRootXmlRoot("Order", Namespace="urn:acme.b2b("Order", Namespace="urn:acme.b2b--schema.v1")]schema.v1")]
public class public class PurchaseOrderPurchaseOrder
{{
[[XmlElementXmlElement("("shipToshipTo")] public Address ")] public Address ShipToShipTo;;
[[XmlElementXmlElement("("billTobillTo")] public Address ")] public Address BillToBillTo;;
[[XmlElementXmlElement("comment")] public string Comment;("comment")] public string Comment;
[[XmlElementXmlElement("items")] public Item[] Items;("items")] public Item[] Items;
[[XmlAttributeXmlAttribute("date")] public ("date")] public DateTime OrderDateDateTime OrderDate;;
}}
public class Address {...}public class Address {...}
public class Item {...}public class Item {...}
AttributesAttributes
Attributes can beAttributes can be
Attached to types and membersAttached to types and members
Examined at runExamined at run--time using reflectiontime using reflection
Completely extensibleCompletely extensible
Simply a class that inherits from Simply a class that inherits from
System.AttributeSystem.Attribute
TypeType--safesafe
Arguments checked at compileArguments checked at compile--timetime
Extensive use in .NET FrameworkExtensive use in .NET Framework
XML, Web Services, security, serialization, XML, Web Services, security, serialization,
component model, COM and P/Invoke interop, component model, COM and P/Invoke interop,
code configuration…code configuration…
XML CommentsXML Comments
classclass XmlElementXmlElement
{{
///
///
/// Returns the attribute with the given name and/// Returns the attribute with the given name and
/// namespace/// namespace
/// //
name="name">
/// The name of the attribute/// The name of the attribute>
/// //
name="ns">
/// The namespace of the attribute, or null if/// The namespace of the attribute, or null if
/// the attribute has no namespace/// the attribute has no namespace>
///
///
/// The attribute value, or null if the attribute/// The attribute value, or null if the attribute
/// does not exist/// does not exist
/// //
(string)"/>
//////
public stringpublic string GetAttrGetAttr(string name, string ns) {(string name, string ns) {
......
}}
}}
Statements And Statements And
ExpressionsExpressions
High C++ fidelityHigh C++ fidelity
If, while, do requireIf, while, do require boolbool conditioncondition
gotogoto can’t jump into blockscan’t jump into blocks
Switch statementSwitch statement
No fallNo fall--through, “through, “gotogoto case” or “case” or “gotogoto default”default”
foreachforeach statementstatement
Checked and unchecked statementsChecked and unchecked statements
Expression statements must do workExpression statements must do work
void Foo() {void Foo() {
i == 1; // errori == 1; // error
}}
foreach foreach StatementStatement
Iteration of arraysIteration of arrays
Iteration of userIteration of user--defined collectionsdefined collections
public static void Main(string[] public static void Main(string[] argsargs) {) {
foreachforeach (string s in(string s in argsargs) Console.) Console.WriteLineWriteLine(s);(s);
}}
foreachforeach (Customer c in customers.(Customer c in customers.OrderByOrderBy("name")) {("name")) {
if (c.Orders.Count != 0) {if (c.Orders.Count != 0) {
......
}}
}}
Parameter ArraysParameter Arrays
Can write “Can write “printfprintf” style methods” style methods
TypeType--safe, unlike C++safe, unlike C++
voidvoid printfprintf(string(string fmtfmt,, paramsparams object[]object[] argsargs) {) {
foreachforeach (object x in(object x in argsargs) {) {
......
}}
}}
printfprintf("%s %i %i",("%s %i %i", strstr, int1, int2);, int1, int2);
object[]object[] argsargs = new object[3];= new object[3];
argsargs[0] = [0] = strstr;;
argsargs[1] = int1;[1] = int1;
ArgsArgs[2] = int2;[2] = int2;
printfprintf("%s %i %i", ("%s %i %i", argsargs););
Operator OverloadingOperator Overloading
First class userFirst class user--defined data typesdefined data types
Used in base class libraryUsed in base class library
Decimal,Decimal, DateTimeDateTime,, TimeSpanTimeSpan
Used in UI libraryUsed in UI library
Unit, Point, RectangleUnit, Point, Rectangle
Used in SQL integrationUsed in SQL integration
SQLStringSQLString, SQLInt16, SQLInt32, , SQLInt16, SQLInt32,
SQLInt64,SQLInt64, SQLBoolSQLBool,, SQLMoneySQLMoney,,
SQLNumericSQLNumeric, , SQLFloatSQLFloat……
Operator OverloadingOperator Overloading
publicpublic struct DBIntstruct DBInt
{{
public staticpublic static readonly DBIntreadonly DBInt Null = newNull = new DBIntDBInt();();
privateprivate intint value;value;
privateprivate boolbool defined;defined;
publicpublic bool IsNullbool IsNull { get { return !defined; } }{ get { return !defined; } }
public staticpublic static DBIntDBInt operator +(operator +(DBIntDBInt x,x, DBIntDBInt y) {...}y) {...}
public static implicit operatorpublic static implicit operator DBIntDBInt((intint x) {...}x) {...}
public static explicit operatorpublic static explicit operator intint((DBIntDBInt x) {...}x) {...}
}}
DBIntDBInt x = 123;x = 123;
DBIntDBInt y =y = DBI