introduction to c # – part 1 stephen turner software design engineer [email protected]...
TRANSCRIPT
Introduction to CIntroduction to C## – Part 1 – Part 1
Stephen TurnerStephen TurnerSoftware Design Software Design
[email protected]@microsoft.co
mmMicrosoft UKMicrosoft UK
AgendaAgenda
Language comparisonsLanguage comparisons – C – C## vs. Java, etc. vs. Java, etc.Program structureProgram structure – Hello, World – Hello, WorldDesign goalsDesign goals – Part 1 – Part 1 Provide unified type systemProvide unified type system Support component-oriented programmingSupport component-oriented programming Dramatically increase productivityDramatically increase productivity
Design goals – Part 2Design goals – Part 2 Fully extensible type systemFully extensible type system Enable robust and durable applicationsEnable robust and durable applications Leverage existing softwareLeverage existing software
Language ComparisonsLanguage Comparisons60% Java, 10% C++, 10% VB, 20% 60% Java, 10% C++, 10% VB, 20% newnew
As in JavaAs in Java Object-orientation Object-orientation
(single inheritance)(single inheritance) NamespacesNamespaces
(like packages)(like packages) InterfacesInterfaces Strong typingStrong typing ExceptionsExceptions ThreadsThreads Garbage collectionGarbage collection ReflectionReflection Dynamic loadingDynamic loading
of codeof code
As in C++As in C++ Operator overloadingOperator overloading Pointer arithmetic in Pointer arithmetic in
unsafe codeunsafe code Some syntactic Some syntactic
detailsdetails
As in VBAs in VB PropertiesProperties EventsEvents RAD developmentRAD development
Language ComparisonsLanguage ComparisonsAdvancements on JavaAdvancements on Java
Really newReally new Objects on the stack Objects on the stack
(structs)(structs) Boxing / unboxingBoxing / unboxing DelegatesDelegates AttributesAttributes Ref and out Ref and out
parametersparameters Rectangular arraysRectangular arrays EnumerationsEnumerations Unified type systemUnified type system gotogoto VersioningVersioning
ProductivityProductivity Component-based Component-based
programmingprogramming PropertiesProperties EventsEvents IndexersIndexers
Operator overloadingOperator overloading foreach statementsforeach statements
AgendaAgenda
Language comparisonsLanguage comparisons – C – C## vs. Java, etc. vs. Java, etc.Program structureProgram structure – Hello, World – Hello, WorldDesign goalsDesign goals – Part 1 – Part 1 Provide unified type systemProvide unified type system Support component-oriented programmingSupport component-oriented programming Dramatically increase productivityDramatically increase productivity
Design goals – Part 2Design goals – Part 2 Fully extensible type systemFully extensible type system Enable robust and durable applicationsEnable robust and durable applications Leverage existing softwareLeverage existing software
Hello, WorldHello, World
class Hello{
static void Main() {
System.Console.WriteLine("Hello, World");}
}
Hello, WorldHello, World
using System;
class Hello{
static void Main() {
Console.WriteLine("Hello, World");}
}
Hello, WorldHello, World
using System;
class Hello{
private static int Main(string[] args){
Console.WriteLine("Hello, World");
return 0;}
}
Hello, WorldHello, World
using System;
namespace Test {class Hello {
static void Main(string[] args) {if (args.Length > 0) {
Person p = new Person(args[0]);Console.WriteLine("Hello, " + p.name);
}}
}
class Person {public string name;public Person(string name) {
this.name = name;}
}}
C# Program StructureC# Program Structure
NamespacesNamespaces Contain types and other namespacesContain types and other namespaces
Type declarationsType declarations class, struct, interface, enum and delegateclass, struct, interface, enum and delegate
MembersMembers constant, field, method, property, indexer, constant, field, method, property, indexer,
event, operator, constructor, destructor event, operator, constructor, destructor (finalizer)(finalizer)
OrganizationOrganization No header files, code written “in-line”No header files, code written “in-line” No declaration order dependenceNo declaration order dependence
AgendaAgenda
Language comparisonsLanguage comparisons – C – C## vs. Java, vs. Java, etc.etc.Program structureProgram structure – Hello, World – Hello, WorldDesign goalsDesign goals – Part 1 – Part 1 Provide unified type systemProvide unified type system Support component-oriented Support component-oriented
programmingprogramming Dramatically increase productivityDramatically increase productivity
Unified Type SystemUnified Type System
Traditional viewsTraditional views C++, Java – primitive types are “magic” C++, Java – primitive types are “magic”
and do not interoperate with objectsand do not interoperate with objects Smalltalk, Lisp – primitive types are Smalltalk, Lisp – primitive types are
objects, but at great performance costobjects, but at great performance cost
C# unifies with little or no performance C# unifies with little or no performance costcost 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 all typesCollections, etc., work for all types
Unified Type SystemUnified Type System
All types ultimately inherit from objectAll types ultimately inherit from objectAny 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
Value & Reference TypesValue & Reference Types
Value typesValue types Variables directly contain dataVariables directly contain data Cannot be nullCannot be null
Reference typesReference types Variables contain references to objectsVariables contain references to objects May be nullMay be null
int i = 123;string s = "Hello world";
123123ii
ss "Hello world""Hello world"
Value & Reference TypesValue & Reference Types
Value typesValue types PrimitivesPrimitives int i; float f;int i; float f; EnumsEnums enum State { Off, On }enum State { Off, On } StructsStructs struct Point { int x, y; }struct Point { int x, y; }
Reference typesReference types ClassesClasses class Foo: Bar, IFoo { … }class Foo: Bar, IFoo { … } InterfacesInterfaces interface IFoo: IBar { … }interface IFoo: IBar { … } ArraysArrays string[] s = new string[] s = new
string[10];string[10]; DelegatesDelegates delegate void Empty();delegate void Empty();
Unified Type SystemUnified Type System
BoxingBoxing Allocates a box, copies value into itAllocates a box, copies value into it
UnboxingUnboxing Checks type of box, copies value outChecks type of box, copies value out
int i = 123;object o = i;int j = (int) o;
123123i
o
123123
System.Int32System.Int32
123123j
Unified Type SystemUnified Type System
BenefitsBenefits Eliminates the need for wrapper classesEliminates the need for wrapper classes Collection classes work with all typesCollection classes work with all types Replaces OLE Automation's VariantReplaces OLE Automation's Variant Simple, consistent programming modelSimple, consistent programming model
string s1 = String.Format("Your balance is {0} on {1}", 24.95, DateTime.Today);
ArrayList al = new ArrayList();al.Add(new Object());al.Add(1);al.Add("Hello");
string s2 = 24.95.ToString(); // no boxing occurs here
Predefined TypesPredefined Types
C# predefined typesC# predefined types ReferenceReference object, stringobject, string SignedSigned sbyte, short, int, longsbyte, short, int, long UnsignedUnsigned byte, ushort, uint, byte, ushort, uint,
ulongulong CharacterCharacter charchar Floating-pointFloating-point float, double, decimalfloat, double, decimal LogicalLogical boolbool
Predefined types are simply aliases for Predefined types are simply aliases for system-provided typessystem-provided types For example, int = System.Int32For example, int = System.Int32
ClassesClasses
InheritanceInheritance Single base classSingle base class Multiple interface implementationMultiple interface implementation
Class membersClass members Constants, fields, methods, properties, Constants, fields, methods, properties,
indexers, events, operators, constructors, indexers, events, operators, constructors, destructorsdestructors
Static and instance membersStatic and instance members Nested typesNested types
Member accessMember access Public, protected, internal, privatePublic, protected, internal, private
InterfacesInterfaces
Specify methods, properties, indexers Specify methods, properties, indexers & events& eventsPublic or private implementationsPublic or private implementations
interface IDataBound {void Bind(IDataBinder binder);
}
class EditBox : Control, IDataBound {void IDataBound.Bind(IDataBinder binder) {
...}
}
StructsStructs
Like classes, exceptLike classes, except Stored on stack or in-line, not heap Stored on stack or in-line, not heap
allocatedallocated Assignment copies data, not referenceAssignment copies data, not reference Derive from System.ValueTypeDerive from System.ValueType Can not inherit or be inheritedCan not inherit or be inherited Can implement multiple interfacesCan implement multiple interfaces
Ideal for light weight objectsIdeal for light weight objects Complex, point, rectangle, colorComplex, point, rectangle, color int, float, double, etc., are all structsint, float, double, etc., are all structs
BenefitsBenefits No heap allocation, so fast!No heap allocation, so fast! More efficient use of memoryMore efficient use of memory
Classes and StructsClasses and Structs
1010
2020spsp
cpcp
1010
2020
CPointCPoint
Class CPoint { int x, y; ... }struct SPoint { int x, y; ... }
CPoint cp = new CPoint(10, 20);SPoint sp = new SPoint(10, 20);
AgendaAgenda
Language comparisonsLanguage comparisons – C – C## vs. Java, vs. Java, etc.etc.Program structureProgram structure – Hello, World – Hello, WorldDesign goalsDesign goals – Part 1 – Part 1 Provide unified type systemProvide unified type system Support component-oriented Support component-oriented
programmingprogramming Dramatically increase productivityDramatically increase productivity
11stst Class Component Class Component SupportSupport
C# is the first “component oriented” C# is the first “component oriented” language in the C/C++ familylanguage in the C/C++ familyWhat defines a component?What defines a component? Properties & eventsProperties & events Design-time & runtime informationDesign-time & runtime information Integrated help & documentationIntegrated help & documentation
C# has first class supportC# has first class support Not naming patterns, adapters, etc.Not naming patterns, adapters, etc. Not external header or IDL filesNot external header or IDL files
Easy to build & consumeEasy to build & consume
public class Person{
private int age;
public int Age {get {
return age;}set {
age = value;Party();
}}
}
// UnnaturalPerson p = new Person();p.set_Age(27);p.set_Age(p.get_Age() + 1);
// NaturalPerson p = new Person();p.Age = 27;p.Age ++;
PropertiesProperties
Properties are “smart fields”Properties are “smart fields” Natural syntax, accessors, inliningNatural syntax, accessors, inlining
IndexersIndexers
Indexers are “smart arrays”Indexers are “smart arrays” Overloadable for different index Overloadable for different index
signaturessignaturespublic class ListBox : Control{
private string[] items;
public string this[int index] {get {
return items[index];}set {
items[index] = value;Repaint();
}}
}
ListBox lb = new ListBox();
lb[0] = "hello";Console.WriteLine(lb[0]);
DelegatesDelegates
Object oriented function pointersObject oriented function pointers Actually a method typeActually a method type
Multiple receiversMultiple receivers Each delegate has an invocation list (+= Each delegate has an invocation list (+=
& -= ops)& -= ops)delegate double Func(double x);
static void Main() {Func f = new Func(MySin);double x = f(1.0);
}
private static double MySin(double x) {return Math.Sin(x);
}
EventsEvents
A “protected delegate”A “protected delegate” Owning class gets full accessOwning class gets full access Consumers can only hook or unhook Consumers can only hook or unhook
handlershandlers Similar to a property – supported with Similar to a property – supported with
metadatametadata
Used throughout the frameworks Used throughout the frameworks Very easy to extendVery easy to extend
Event SourcingEvent Sourcing
Define the event signatureDefine the event signature
Define the event and firing logicDefine the event and firing logic
public delegate void EventHandler(object sender, EventArgs e);
public class Button : Control{
public event EventHandler Click;
protected void OnClick(EventArgs e) {if (Click != null) {
Click(this, e);}
}}
Event HandlingEvent Handling
Define and register event handlerDefine and register event handler
public class MyForm : Form{
Button okButton;
public MyForm() {okButton = new Button();okButton.Text = "OK";okButton.Click += new EventHandler(OkButtonClick);
}
private void OkButtonClick(object sender, EventArgs e) {MessageBox.Show("You pressed the OK button");
}}
MetadataMetadata
Associate with types and membersAssociate with types and members Design time informationDesign time information Transaction context for a methodTransaction context for a method XML persistence mappingXML persistence mapping
Traditional solutionsTraditional solutions Add keywords or pragmas to languageAdd keywords or pragmas to language Use external files, e.g., .IDL, .DEFUse external files, e.g., .IDL, .DEF
Extend the language semanticsExtend the language semantics Expose methods to web servicesExpose methods to web services Set transaction context for a methodSet transaction context for a method
AttributesAttributes
Attributes can beAttributes can be Attached to any type and its membersAttached to any type and its members Examined at run-time using reflectionExamined at run-time using reflection
Completely extensibleCompletely extensible Simply a class that inherits from Simply a class that inherits from
System.AttributeSystem.AttributeType-safeType-safe Arguments checked at compile-timeArguments checked at compile-time
Extensive use in .NET frameworkExtensive use in .NET framework Web Services, code security, serialization, Web Services, code security, serialization,
XML persistence, component / control XML persistence, component / control model, COM and P/Invoke interop, code model, COM and P/Invoke interop, code configuration…configuration…
AttributesAttributes
Appear in square bracketsAppear in square bracketsAttached to code elementsAttached to code elements Types, members & parametersTypes, members & parameters
[WebService(Namespace="http://microsoft.com/demos/")]class SomeClass{
[WebMethod]void GetCustomers() {}
string Test([SomeAttr] string param1) {}
}
Creating AttributesCreating Attributes
Attributes are simply classesAttributes are simply classes Derived from System.AttributeDerived from System.Attribute Class functionality = attribute Class functionality = attribute
functionalityfunctionalitypublic class HelpURLAttribute : System.Attribute{
public HelpURLAttribute(string url) { … }
public string URL { get { … } }public string Tag { get { … } set { … } }
}
Using AttributesUsing Attributes
Just attach it to a classJust attach it to a class
Use named parametersUse named parameters
Use multiple attributesUse multiple attributes
[HelpURL(“http://someurl/”)]Class MyClass { … }
[HelpURL(“http://someurl/”, Tag=“ctor”)]Class MyClass { … }
[HelpURL(“http://someurl/”), HelpURL(“http://someurl/”, Tag=“ctor”)]Class MyClass { … }
Querying AttributesQuerying Attributes
Use reflection to query attributesUse reflection to query attributesType type = typeof(MyClass); // or myObj.GetType()
foreach (Attribute attr in type.GetCustomAttributes()){
if (attr is HelpURLAttribute){
HelpURLAttribute ha = (HelpURLAttribute) attr;myBrowser.Navigate(ha.URL);
}}
AgendaAgenda
Language comparisonsLanguage comparisons – C – C## vs. Java, vs. Java, etc.etc.Program structureProgram structure – Hello, World – Hello, WorldDesign goalsDesign goals – Part 1 – Part 1 Provide unified type systemProvide unified type system Support component-oriented Support component-oriented
programmingprogramming Dramatically increase productivityDramatically increase productivity
Productivity FeaturesProductivity Features
EnumsEnumsforeach statementforeach statementParameter arraysParameter arraysRef and out Ref and out parametersparametersOverflow checkingOverflow checkingUsing statementUsing statement
Switch on stringSwitch on stringOperator overloadingOperator overloadingXML commentsXML commentsConditional Conditional compilationcompilationUnsafe codeUnsafe codePlatform InvokePlatform InvokeCOM interopCOM interop
EnumsEnums
Strongly typedStrongly typed No implicit conversions to/from intNo implicit conversions to/from int Operators: +, -, ++, --, &, |, ^, ~Operators: +, -, ++, --, &, |, ^, ~
Can specify underlying typeCan specify underlying type Byte, short, int, longByte, short, int, long
Supported my metadata & reflectionSupported my metadata & reflectionenum Color: byte {
Red = 1,Green = 2,Blue = 4,Black = 0,White = Red | Green | Blue,
}
foreach Statementforeach Statement
Iteration of arraysIteration of arrays
Iteration of user-defined collectionsIteration of user-defined collections Or any type that supports IEnumerableOr any type that supports IEnumerable
foreach (Customer c in customers.OrderBy("name")) {
if (c.Orders.Count != 0) {...
}}
public static void Main(string[] args) {foreach (string s in args) {
Console.WriteLine(s);}
}
static void Main() {printf("%s %i %o", "Hello", 29, new Object());
object[] args = new object[3];args[0] = "Hello";args[1] = 29;args[2] = new Object();printf("%s %i %o", args);
}
static void printf(string fmt, params object[] args) {foreach (object x in args) {}
}
Parameter ArraysParameter Arrays
Can write “printf” style methodsCan write “printf” style methods Type-safe, unlike C++Type-safe, unlike C++
ref and out Parametersref and out Parameters
Use “ref” for in/out parameter passingUse “ref” for in/out parameter passingUse “out” to return multiple valuesUse “out” to return multiple valuesMust repeat ref/out at call siteMust repeat ref/out at call site
static void Swap(ref int a, ref int b) {...}
static void Divide(int dividend, int divisor,out int result, out int remainder) {...}
static void Main() {int x = 1, y = 2;Swap(ref x, ref y);int r0, r1;Divide(3, 2, out r0, out r1);
}
Overflow CheckingOverflow Checking
Integer arithmetic operationsInteger arithmetic operations C, C++, Java silently overflowC, C++, Java silently overflow
checked vs. unchecked contextschecked vs. unchecked contexts Default is unchecked, except for Default is unchecked, except for
constantsconstants Change with “/checked” compiler switchChange with “/checked” compiler switch
int m0 = checked(x * y);
checked {int m1 = x * y;
}
using Statementusing Statement
Acquire, Execute, Release patternAcquire, Execute, Release patternWorks with any IDisposable objectWorks with any IDisposable object Data access classes, streams, text Data access classes, streams, text
readers and writers, network classes, etc.readers and writers, network classes, etc.Resource res = new Resource(...);try {
res.DoWork();}finally {
if (res != null) {((IDisposable)res).Dispose();
}} using (Resource res = new Resource()) {
res.DoWork();}
Switch on StringSwitch on String
Color ColorFromFruit(string s){
switch(s.ToLower()){
case "apple":return Color.Red;
case "banana":return Color.Yellow;
case "carrot":return Color.Orange;
default:throw new InvalidArgumentException();
}}
Operator OverloadingOperator Overloading
First class user-defined data typesFirst class user-defined data typesUsed in base class libraryUsed in base class library Decimal, DateTime, TimeSpanDecimal, DateTime, TimeSpan
Used in the Windows Forms libraryUsed in the Windows Forms library Point, Size, RectanglePoint, Size, Rectangle
Used in the SQL librariesUsed in the SQL libraries SQLString, SQLInt16, SQLInt32, SQLString, SQLInt16, SQLInt32,
SQLInt64, SQLBool, SQLMoney, SQLInt64, SQLBool, SQLMoney, SQLNumeric, SQLFloat…SQLNumeric, SQLFloat…
Operator OverloadingOperator Overloading
public struct DBInt{
public static readonly DBInt Null = new DBInt();
private int value;private bool defined;
public bool IsNull { get { return !defined; } }
public static DBInt operator +(DBInt x, DBInt y) {...}
public static implicit operator DBInt(int x) {...}public static explicit operator int(DBInt x) {...}
}
DBInt x = 123;DBInt y = DBInt.Null;DBInt z = x + y;
XML CommentsXML Comments
/// denotes an XML comment/// denotes an XML commentCompiler processing:Compiler processing: Verifies well-formed XMLVerifies well-formed XML Verifies parameter namesVerifies parameter names Generates globally unique names, so links Generates globally unique names, so links
can be resolvedcan be resolved
Any XML is okay, can use “standard” Any XML is okay, can use “standard” tags if you want totags if you want toEnables post-processing to final formEnables post-processing to final form
XML CommentsXML Comments
class XmlElement{
/// <summary>/// Returns the attribute with the given name/// </summary>/// <param name="name">/// The name of the attribute/// </param>/// <return>/// The attribute value, or null/// </return>/// <seealso cref="GetAttr(string)"/>
public string GetAttribute(string name) {...
}}
Conditional CompilationConditional Compilation
#define, #undef#define, #undef#if, #elif, #else, #endif#if, #elif, #else, #endif Simple boolean logicSimple boolean logic
Macros are not supportedMacros are not supportedConditional methodsConditional methods
public class Debug {
[Conditional("Debug")]public static void Assert(bool cond, String s) {
if (!cond) {throw new AssertionException(s);
}}
}
SummarySummary
Language comparisonsLanguage comparisons – C – C## vs. Java, etc. vs. Java, etc.Program structureProgram structure – Hello, World – Hello, WorldDesign goalsDesign goals – Part 1 – Part 1 Provide unified type systemProvide unified type system Support component-oriented programmingSupport component-oriented programming Dramatically increase productivityDramatically increase productivity
Design goals – Part 2Design goals – Part 2 Fully extensible type systemFully extensible type system Enable robust and durable applicationsEnable robust and durable applications Leverage existing softwareLeverage existing software
© 2003 Microsoft Ltd. All rights reserved.© 2003 Microsoft Ltd. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.