Beyond the EU: DORA and NIS 2 Directive's Global Impact
C# Intro: Learn .NET Framework & Language Features
1.
2. Introduction to C#Introduction to C#
Raimonds RudmanisRaimonds Rudmanis
Senior ConsultantSenior Consultant
MicrosoftMicrosoft BalticBaltic
3. Session PrerequisitesSession Prerequisites
This session assumes that youThis session assumes that you
understand the fundamentals ofunderstand the fundamentals of
Object oriented programmingObject oriented programming
This is a Level 200 SessionThis is a Level 200 Session
4. What Will Be Covered TodayWhat Will Be Covered Today
Brief introduction to theBrief introduction to the
.NET framework.NET framework
C# language overviewC# language overview
5. AgendaAgenda
Hello WorldHello World
The .NET FrameworkThe .NET Framework
Design Goals of C#Design Goals of C#
Language FeaturesLanguage Features
6. Hello WorldHello World
DEMO 1: Hello WorldDEMO 1: Hello World
using System;using System;
class Helloclass Hello
{{
static void Main() {static void Main() {
Console.WriteLine("Hello world");Console.WriteLine("Hello world");
}}
}}
7. AgendaAgenda
Hello WorldHello World
The .NET FrameworkThe .NET Framework
Design Goals of C#Design Goals of C#
Language FeaturesLanguage Features
8. The .NET FrameworkThe .NET Framework
OverviewOverview
Base Class LibraryBase Class Library
Common Language SpecificationCommon Language Specification
Common Language RuntimeCommon Language Runtime
ADO.NET: Data and XMLADO.NET: Data and XML
VBVB C++C++ C#C#
VisualStudio.NETVisualStudio.NET
ASP.NET: Web ServicesASP.NET: Web Services
And Web FormsAnd Web Forms
JScriptJScript ……
WindowsWindows
formsforms
9. The .NET FrameworkThe .NET Framework
Common Language RuntimeCommon Language Runtime
Base Class LibraryBase Class Library
Common Language SpecificationCommon Language Specification
Common Language RuntimeCommon Language Runtime
ADO.NET: Data and XMLADO.NET: Data and XML
VBVB C++C++ C#C#
VisualStudio.NETVisualStudio.NET
ASP.NET: Web ServicesASP.NET: Web Services
and Web Formsand Web Forms
JScriptJScript ……
WindowsWindows
FormsForms
10. New Runtime Environment – CommonNew Runtime Environment – Common
Language RuntimeLanguage Runtime
Language InteroperabilityLanguage Interoperability
Common Classes for all LanguagesCommon Classes for all Languages
Common Types for all LanguagesCommon Types for all Languages
Runtime Controls Compilation to MachineRuntime Controls Compilation to Machine
CodeCode
AssembliesAssemblies
Application DomainsApplication Domains
The .NET FrameworkThe .NET Framework
Common Language RuntimeCommon Language Runtime
11. The .NET FrameworkThe .NET Framework
Common Language RuntimeCommon Language Runtime
Simplified developmentSimplified development
XCOPY deploymentXCOPY deployment
ScalabilityScalability
Rich Web clients and safe Web hostingRich Web clients and safe Web hosting
Potentially multi-platformPotentially multi-platform
Multiple languages (cross inheritance)Multiple languages (cross inheritance)
Increases productivityIncreases productivity
Robust and secure execution environmentRobust and secure execution environment
12. .NET Framework and CLR.NET Framework and CLR
CLR Execution ModelCLR Execution Model
VBVBSourceSource
codecode
CompilerCompiler
C++C++C#C#
CompilerCompilerCompilerCompiler
AssemblyAssembly
IL CodeIL Code
AssemblyAssembly
IL CodeIL Code
AssemblyAssembly
IL CodeIL Code
Operating System ServicesOperating System Services
Common Language RuntimeCommon Language Runtime
JIT CompilerJIT Compiler
Native CodeNative Code
ManagedManaged
codecode
UnmanagedUnmanaged
ComponentComponent
13. The .NET FrameworkThe .NET Framework
.NET Framework Services.NET Framework Services
Base Class LibraryBase Class Library
Common Language SpecificationCommon Language Specification
Common Language RuntimeCommon Language Runtime
ADO.NET: Data and XMLADO.NET: Data and XML
VBVB C++C++ C#C#
VisualStudio.NETVisualStudio.NET
ASP.NET: Web ServicesASP.NET: Web Services
and Web Formsand Web Forms
JScriptJScript ……
WindowsWindows
FormsForms
14. The .NET FrameworkThe .NET Framework
.NET Framework Services.NET Framework Services
ASP.NETASP.NET
Separation of code and presentationSeparation of code and presentation
CompiledCompiled
Web FormsWeb Forms
Web ServicesWeb Services
WindowsWindows®®
FormsForms
Framework for building rich clientsFramework for building rich clients
ADO.NET, Evolution of ADOADO.NET, Evolution of ADO
New objects (e.g., DataSets)New objects (e.g., DataSets)
XML support throughoutXML support throughout
15. AgendaAgenda
Hello WorldHello World
The .NET FrameworkThe .NET Framework
Design Goals of C#Design Goals of C#
Language FeaturesLanguage Features
16. Design Goals of C#Design Goals of C#
The Big IdeasThe Big Ideas
The firstThe first “C“Componentomponent OOrientedriented””
language in the C/C++ familylanguage in the C/C++ family
Everything really is an objectEverything really is an object
Next generation robust andNext generation robust and
durable softwaredurable software
Preserving your investmentPreserving your investment
17. Design Goals of C#Design Goals of C#
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 classComponent concepts are first class
Properties, methods, eventsProperties, methods, events
Design-time and run-time attributesDesign-time and run-time attributes
Integrated documentation using XMLIntegrated documentation using XML
Enables one-stop programmingEnables one-stop programming
NoNo external files likeexternal files like header files, IDL, etc.header files, IDL, etc.
Can be embedded in ASP pagesCan be embedded in ASP pages
18. Design Goals of C#Design Goals of C#
Everything Really Is an ObjectEverything Really Is an Object
Traditional viewsTraditional views
C++, JavaC++, Java™™
: Primitive types are “magic”: Primitive types are “magic”
and do not interoperate with objectsand do not interoperate with objects
Smalltalk, Lisp: Primitive types areSmalltalk, Lisp: Primitive types are
objects, but at great performance costobjects, but at 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 all typesCollections, etc., work for all types
19. Design Goals of C#Design Goals of C#
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
Type-safetyType-safety
No uninitialized variables, unsafe castsNo uninitialized variables, unsafe casts
VersioningVersioning
Pervasive versioning considerations in allPervasive versioning considerations in all
aspects of language designaspects of language design
20. Design Goals of C#Design Goals of C#
Preserving Your InvestmentPreserving Your Investment
C++ HeritageC++ Heritage
Namespaces,Namespaces, enums,enums, pointers (in unsafepointers (in unsafe
code), unsigned types, etc.code), unsigned types, etc.
No unnecessary sacrificesNo unnecessary sacrifices
Real-world useful constructsReal-world useful constructs
foreach, using, switch on stringforeach, using, switch on string
decimal type for financial applicationsdecimal type for financial applications
ref and out parametersref and out parameters
Millions of lines of C# code in .NETMillions of lines of C# code in .NET
Short learning curveShort learning curve
Increased productivityIncreased productivity
21. Design Goals of C#Design Goals of C#
InteroperabilityInteroperability
C#C#
VB.NETVB.NET
MC++MC++
JScriptJScript
......
.NET Languages.NET Languages
COMCOM
OLE AutomationOLE Automation
XML/SOAPXML/SOAP
Dynamic Link LibrariesDynamic Link Libraries
P/Invoke and unsafe codeP/Invoke and unsafe code
22. AgendaAgenda
Hello WorldHello World
The .NET FrameworkThe .NET Framework
Design Goals of C#Design Goals of C#
Language FeaturesLanguage Features
23. Language FeaturesLanguage Features
Program StructureProgram Structure
NamespacesNamespaces
Contain types and other namespacesContain types and other namespaces
Type declarationsType declarations
Classes, structs, interfaces, enums,Classes, structs, interfaces, enums,
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 “in-line”No header files, code written “in-line”
No declaration order dependenceNo declaration order dependence
24. Language FeaturesLanguage Features
Program StructureProgram 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 InvalidOperationException();if (top == null) throw new InvalidOperationException();
object result = top.data;object result = top.data;
top = top.next;top = top.next;
return result;return result;
}}
}}
}}
25. Language FeaturesLanguage Features
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
int i = 123;int i = 123;
string s = "Hello world";string s = "Hello world";
123123ii
ss "Hello world""Hello world"
26. Language FeaturesLanguage Features
Type SystemType System
Value typesValue types
PrimitivesPrimitives int i;int i;
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[] a = new string[10];string[] a = new string[10];
DelegatesDelegates delegate void Empty();delegate void Empty();
27. Language FeaturesLanguage Features
Predefined TypesPredefined Types
C# predefined typesC# predefined types
ReferenceReference object, stringobject, string
SignedSigned sbyte, short, int, longsbyte, short, int, long
UnsignedUnsigned byte, ushort, uint, ulongbyte, ushort, uint, ulong
CharacterCharacter charchar
Floating-pointFloating-point float, double, decimalfloat, double, decimal
LogicalLogical boolbool
Predefined types are simply aliases forPredefined types are simply aliases for
system-provided typessystem-provided types
For example, int = System.Int32For example, int = System.Int32
28. Language FeaturesLanguage Features
ClassesClasses
Single inheritanceSingle inheritance
Multiple interface implementationMultiple interface implementation
Class membersClass members
Constants, fields, methods,Constants, fields, methods,
properties, indexers, events,properties, indexers, events,
operators, constructors, destructorsoperators, constructors, destructors
Static and instance membersStatic and instance members
Nested typesNested types
Member accessMember access
Public, protected, internal, privatePublic, protected, internal, private
29. Language FeaturesLanguage Features
StructsStructs
Like classes, exceptLike classes, except
Stored in-line, not heap allocatedStored in-line, 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
int, float, double, etc., are all structsint, float, double, etc., are all structs
BenefitsBenefits
No heap allocation, less GC pressureNo heap allocation, less GC pressure
More efficient use of memoryMore efficient use of memory
30. Language FeaturesLanguage Features
Classes and StructsClasses and Structs
struct SPoint { int x, y; ... }struct SPoint { int x, y; ... }
class CPoint { int x, y; ... }class CPoint { int x, y; ... }
SPoint sp = new SPoint(10, 20);SPoint sp = new SPoint(10, 20);
CPoint cp = new CPoint(10, 20);CPoint cp = new CPoint(10, 20);
1010
2020
spsp
cpcp
1010
2020
CPointCPoint
31. Language FeaturesLanguage Features
InterfacesInterfaces
Multiple inheritanceMultiple inheritance
Can contain methods, properties,Can contain methods, properties,
indexers and eventsindexers and events
Private interface implementationsPrivate interface implementations
interface IDataBoundinterface IDataBound
{{
void Bind(IDataBinder binder);void Bind(IDataBinder binder);
}}
class EditBox: Control, IDataBoundclass EditBox: Control, IDataBound
{{
void IDataBound.Bind(IDataBinder binder) {...}void IDataBound.Bind(IDataBinder binder) {...}
}}
32. Language FeaturesLanguage Features
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
enum Color: byteenum Color: 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,
}}
33. Language FeaturesLanguage Features
DelegatesDelegates
Object oriented function pointersObject oriented function pointers
Multiple receiversMultiple receivers
Each delegate has an invocation listEach delegate has an invocation list
Thread-safe + and - operationsThread-safe + and - operations
Foundation for framework eventsFoundation for framework events
delegate void MouseEvent(int x, int y);delegate void MouseEvent(int x, int y);
delegate double Func(double x);delegate double Func(double x);
Func func = new Func(Math.Sin);Func func = new Func(Math.Sin);
double x = func(1.0);double x = func(1.0);
34. Language FeaturesLanguage Features
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 notransported, and manipulated with no
extra workextra work
StreamStream
MemoryStreamMemoryStream FileStreamFileStream
HashtableHashtable doubledoubleintint
objectobject
35. Language FeaturesLanguage Features
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
int i = 123;int i = 123;
object o = i;object o = i;
int j = (int)o;int j = (int)o;
123123i
o
123123
System.Int32System.Int32
123123j
36. Language FeaturesLanguage Features
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);
ArrayList al = new ArrayList();ArrayList al = new ArrayList();
al.Add( new Customer() );al.Add( new Customer() );
al.Add( 1 );al.Add( 1 );
al.Add( "test" );al.Add( "test" );
37. Language FeaturesLanguage Features
Component DevelopmentComponent Development
What defines a component?What defines a component?
Properties, methods, eventsProperties, methods, events
Integrated help and documentationIntegrated help and documentation
Design-time informationDesign-time 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 andComponents are easy to build and
to consumeto consume
38. Language FeaturesLanguage Features
PropertiesProperties
Properties Are “Smart Fields”Properties Are “Smart Fields”
Natural syntax, accessors, inliningNatural syntax, accessors, inlining
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;
39. Language FeaturesLanguage Features
IndexersIndexers
Indexers are “smart arrays”Indexers are “smart arrays”
Can be overloadedCan be overloaded
public class ListBox: Controlpublic class ListBox: Control
{{
private string[] items;private string[] items;
public string this[intpublic string this[int
index] {index] {
get {get {
return items[index];return items[index];
}}
set {set {
items[index] = value;items[index] = value;
Repaint();Repaint();
}}
}}
}}
ListBox listBox = newListBox listBox = new
ListBox();ListBox();
listBox[0] = "hello";listBox[0] = "hello";
Console.WriteLine(listBox[0]);Console.WriteLine(listBox[0]);
40. Language FeaturesLanguage Features
Creating and Firing an EventCreating and Firing an Event
Define the Event signatureDefine the Event signature
Define the Event and firing logicDefine the Event and firing logic
public delegate void EventHandler(object sender,public delegate void EventHandler(object sender,
EventArgs e);EventArgs e);
public class Buttonpublic class Button
{{
public event EventHandler Click;public event EventHandler Click;
protected void OnClick(EventArgs e) {protected void OnClick(EventArgs e) {
if (Click != null) Click(this, e);if (Click != null) Click(this, e);
}}
}}
41. Language FeaturesLanguage Features
Handling an EventHandling an Event
Define and register Event HandlerDefine and register Event Handler
public class MyForm: Formpublic class MyForm: Form
{{
Button okButton;Button okButton;
public MyForm() {public MyForm() {
okButton = new Button(...);okButton = new Button(...);
okButton.Caption = "OK";okButton.Caption = "OK";
okButton.Click +=okButton.Click += new EventHandler(OkButtonClick);new EventHandler(OkButtonClick);
}}
void OkButtonClick(object sender, EventArgs e) {void OkButtonClick(object sender, EventArgs e) {
ShowMessage("You pressed the OK button");ShowMessage("You pressed the OK button");
}}
}}
42. Language FeaturesLanguage Features
DEMO 2: Creating an Event HandlerDEMO 2: Creating an Event Handler
Define an Event Handler for a button in aDefine an Event Handler for a button in a
Windows Forms applicationWindows Forms application
43. Language FeaturesLanguage Features
AttributesAttributes
Associate information with typesAssociate information with types
and membersand 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 pragmas to languageAdd keywords or pragmas to language
Use external files, e.g., .IDL, .DEFUse external files, e.g., .IDL, .DEF
C# solution: AttributesC# solution: Attributes
44. Language FeaturesLanguage Features
AttributesAttributes
public class OrderProcessorpublic class OrderProcessor
{{
[WebMethod][WebMethod]
public void SubmitOrder(PurchaseOrder order) {...}public void SubmitOrder(PurchaseOrder order) {...}
}}
[XmlRoot("Order", Namespace="urn:acme.b2b-schema.v1")][XmlRoot("Order", Namespace="urn:acme.b2b-schema.v1")]
public class PurchaseOrderpublic class PurchaseOrder
{{
[XmlElement("shipTo")] public Address ShipTo;[XmlElement("shipTo")] public Address ShipTo;
[XmlElement("billTo")] public Address BillTo;[XmlElement("billTo")] public Address BillTo;
[XmlElement("comment")] public string Comment;[XmlElement("comment")] public string Comment;
[XmlElement("items")] public Item[] Items;[XmlElement("items")] public Item[] Items;
[XmlAttribute("date")] public DateTime OrderDate;[XmlAttribute("date")] public DateTime OrderDate;
}}
public class Address {...}public class Address {...}
public class Item {...}public class Item {...}
45. Language FeaturesLanguage Features
AttributesAttributes
Attributes can beAttributes can be
Attached to types and membersAttached to types and members
Examined at run-time using reflectionExamined at run-time using reflection
Completely extensibleCompletely extensible
Simply a class that inherits from System.AttributeSimply a class that inherits from System.Attribute
Type-safeType-safe
Arguments checked at compile-timeArguments checked at compile-time
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…
46. What Is A Web Service?What Is A Web Service?
HTML = user-to-machineHTML = user-to-machine
XML/SOAP = machine-to-machineXML/SOAP = machine-to-machine
Leveraging the WebLeveraging the Web
Same infrastructureSame infrastructure
Same programming modelSame programming model
Anyone can playAnyone can play
Truly scalable distributed applicationsTruly scalable distributed applications
Stateless and loosely coupledStateless and loosely coupled
Both Internet and intranetBoth Internet and intranet
47. DiscoveryDiscovery
Let’s talk (SOAP)Let’s talk (SOAP)
How Does It Work?How Does It Work?
http://myservice.comhttp://myservice.com
HTML or XML with link to WSDLHTML or XML with link to WSDL
How do we talk? (WSDL)How do we talk? (WSDL)
http://myservice.com?wsdlhttp://myservice.com?wsdl
XML with service descriptionsXML with service descriptions
http://myservice.com/svc1http://myservice.com/svc1
XML/SOAP BODYXML/SOAP BODY
WebWeb
ServiceService
WebWeb
ServiceService
ConsumerConsumer
UDDIUDDI
Find a ServiceFind a Service
http://www.uddi.orghttp://www.uddi.org
Link to DISCO or WSDL documentLink to DISCO or WSDL document
48. Web Services With .NETWeb Services With .NET
ProgramsPrograms
ObjectsObjects
ClassesClasses
MethodsMethods
CallsCalls
WebWeb
XMLXML
XSDXSD
WSDLWSDL
SOAPSOAP
DataData
SchemaSchema
ServicesServices
InvocationInvocation
ApplicationApplication
ConceptsConcepts
The .NET framework providesThe .NET framework provides
a bi-directional mappinga bi-directional mapping
49. Web Services With .NETWeb Services With .NET
public class OrderProcessorpublic class OrderProcessor
{{
public void SubmitOrder(PurchaseOrder order) {...}public void SubmitOrder(PurchaseOrder order) {...}
}}
public class PurchaseOrderpublic class PurchaseOrder
{{
public string ShipTo;public string ShipTo;
public string BillTo;public string BillTo;
public string Comment;public string Comment;
public Item[] Items;public Item[] Items;
public DateTime OrderDate;public DateTime OrderDate;
}}
public class OrderProcessorpublic class OrderProcessor
{{
[WebMethod][WebMethod]
public void SubmitOrder(PurchaseOrder order) {...}public void SubmitOrder(PurchaseOrder order) {...}
}}
[XmlRoot("Order", Namespace="urn:acme.b2b-schema.v1")][XmlRoot("Order", Namespace="urn:acme.b2b-schema.v1")]
public class PurchaseOrderpublic class PurchaseOrder
{{
[XmlElement("shipTo")][XmlElement("shipTo")] public string ShipTo;public string ShipTo;
[XmlElement("billTo")][XmlElement("billTo")] public string BillTo;public string BillTo;
[XmlElement("comment")][XmlElement("comment")] public string Comment;public string Comment;
[XmlElement("items")][XmlElement("items")] public Item[] Items;public Item[] Items;
[XmlAttribute("date")][XmlAttribute("date")] public DateTime OrderDate;public DateTime OrderDate;
}}
PurchaseOrder po = new PurchaseOrder();PurchaseOrder po = new PurchaseOrder();
po.ShipTo = “Anders Hejlsberg";po.ShipTo = “Anders Hejlsberg";
po.BillTo = “Bill Gates";po.BillTo = “Bill Gates";
po.OrderDate = DateTime.Today;po.OrderDate = DateTime.Today;
……
OrderProcessor.SubmitOrder(po);OrderProcessor.SubmitOrder(po);
<?xml version="1.0" encoding="utf-8"?><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope><soap:Envelope>
<soap:Body><soap:Body>
<SubmitOrder><SubmitOrder>
<Order date=“20010703"><Order date=“20010703">
<shipTo>Anders Hejlsberg</shipTo><shipTo>Anders Hejlsberg</shipTo>
<billTo>Bill Gates</billTo><billTo>Bill Gates</billTo>
<comment>Overnight delivery</comment><comment>Overnight delivery</comment>
<items><items>
<productId>17748933</productId><productId>17748933</productId>
<description>Dom Perignon</description><description>Dom Perignon</description>
</items></items>
</Order></Order>
</SubmitOrder></SubmitOrder>
</soap:Body></soap:Body>
</soap:Envelope></soap:Envelope>
50. Language FeaturesLanguage Features
DEMO 3: AttributesDEMO 3: Attributes
Create a Web service by using theCreate a Web service by using the
[[WWebebMMethod] attributeethod] attribute
51. Language FeaturesLanguage Features
XML CommentsXML Comments
class XmlElementclass XmlElement
{{
/// <summary>/// <summary>
/// Returns the attribute with the given name and/// Returns the attribute with the given name and
/// namespace</summary>/// namespace</summary>
/// <param name="name">/// <param name="name">
/// The name of the attribute</param>/// The name of the attribute</param>
/// <param name="ns">/// <param name="ns">
/// The namespace of the attribute, or null if/// The namespace of the attribute, or null if
/// the attribute has no namespace</param>/// the attribute has no namespace</param>
/// <return>/// <return>
/// The attribute value, or null if the attribute/// The attribute value, or null if the attribute
/// does not exist</return>/// does not exist</return>
/// <seealso cref="GetAttr(string)"/>/// <seealso cref="GetAttr(string)"/>
//////
public string GetAttr(string name, string ns) {public string GetAttr(string name, string ns) {
......
}}
}}
52. Language FeaturesLanguage Features
DEMO 4: XML CommentsDEMO 4: XML Comments
Show how the compiler can auto generateShow how the compiler can auto generate
documentation from the source code usingdocumentation from the source code using
XML commentsXML comments
53. Language FeaturesLanguage Features
Statements and ExpressionsStatements and Expressions
High C++ fidelityHigh C++ fidelity
if, while, do require bool conditionif, while, do require bool condition
Switch statementSwitch statement
No fall-through, “goto case” or “goto default”No fall-through, “goto case” or “goto default”
Goto can’t jump into blocksGoto can’t jump into blocks
Foreach statementForeach statement
Checked andChecked and
uncheckedunchecked
statementsstatements
ExpressionExpression
statementsstatements
must do workmust do work
void Foo() {void Foo() {
i == 1;i == 1; // error// error
i + j;i + j; // error// error
}}
switch( arg )switch( arg )
{{
case 0:case 0:
case 1:case 1:
Console.WriteLine(“Low”);Console.WriteLine(“Low”);
case 2:case 2:
Console.WriteLine(“Med”);Console.WriteLine(“Med”);
break;break;
default:default:
Console.WriteLine(“High”);Console.WriteLine(“High”);
}}
switch( arg )switch( arg )
{{
case 0:case 0:
case 1:case 1:
Console.WriteLine(“Low”);Console.WriteLine(“Low”);
break;break;
case 2:case 2:
Console.WriteLine(“Med”);Console.WriteLine(“Med”);
break;break;
default:default:
Console.WriteLine(“High”);Console.WriteLine(“High”);
}}
switch( arg )switch( arg )
{{
case 0:case 0:
case 1:case 1:
Console.WriteLine(“Low”);Console.WriteLine(“Low”);
goto case 2;goto case 2;
case 2:case 2:
Console.WriteLine(“Med”);Console.WriteLine(“Med”);
break;break;
default:default:
Console.WriteLine(“High”);Console.WriteLine(“High”);
}}
int i;int i;
if ( i ) //if ( i ) // errorerror
if ( i>0 )if ( i>0 )
FileClass file;FileClass file;
if ( file = OpenFile() ) //if ( file = OpenFile() ) // errorerror
if ( (file = OpenFile()) != NULL )if ( (file = OpenFile()) != NULL )
foreach ( string word in myArray.words )foreach ( string word in myArray.words )
{{
Console.WriteLine(“{0}”, word)Console.WriteLine(“{0}”, word)
}}
static short x = 32767; // Max shortstatic short x = 32767; // Max short
static short y = 32767;static short y = 32767;
trytry
{{
z =z = checkedchecked((short)(x + y));((short)(x + y));
}}
catch (OverflowException e)catch (OverflowException e)
{{
Console.WriteLine(e.ToString());Console.WriteLine(e.ToString());
}}
goto in_label;goto in_label;
while ( i<100 )while ( i<100 )
{{
in_label:in_label:
i++;i++;
}}
while ( i<100 )while ( i<100 )
{{
if ( j>50 )if ( j>50 )
goto out_label;goto out_label;
}}
out_label:out_label:
54. Language FeaturesLanguage Features
For Each StatementFor Each Statement
Iteration of arraysIteration of arrays
Iteration of user-defined collectionsIteration of user-defined collections
foreach (Customer c in customers.OrderBy("name")) {foreach (Customer c in customers.OrderBy("name")) {
if (c.Orders.Count != 0) {if (c.Orders.Count != 0) {
......
}}
}}
public static void Main(string[] args) {public static void Main(string[] args) {
foreach (string s in args) Console.WriteLine(s);foreach (string s in args) Console.WriteLine(s);
}}
55. Language FeaturesLanguage Features
Parameter ArraysParameter Arrays
Can write “printf” style methodsCan write “printf” style methods
Type-safe, unlike C++Type-safe, unlike C++
void printf(string fmt, params object[] args) {void printf(string fmt, params object[] args) {
foreach (object x in args) {foreach (object x in args) {
......
}}
}}
printf("%s %i %i", str, int1, int2);printf("%s %i %i", str, int1, int2);
object[] args = new object[3];object[] args = new object[3];
args[0] = str;args[0] = str;
args[1] = int1;args[1] = int1;
Args[2] = int2;Args[2] = int2;
printf("%s %i %i", args);printf("%s %i %i", args);
56. Language FeaturesLanguage Features
Operator OverloadingOperator Overloading
First class user-defined data typesFirst class user-defined data types
Used in base class libraryUsed in base class library
Decimal, DateTime, TimeSpanDecimal, DateTime, TimeSpan
Used in the frameworkUsed in the framework
Unit, point, rectangleUnit, point, rectangle
Used in SQL integrationUsed in SQL integration
SQLString, SQLInt16, SQLInt32,SQLString, SQLInt16, SQLInt32,
SQLInt64, SQLBool, SQLMoney,SQLInt64, SQLBool, SQLMoney,
SQLNumeric, SQLFloat…SQLNumeric, SQLFloat…
57. Language FeaturesLanguage Features
Operator OverloadingOperator Overloading
public struct DBIntpublic struct DBInt
{{
public static readonly DBInt Null = new DBInt();public static readonly DBInt Null = new DBInt();
private int value;private int value;
private bool defined;private bool defined;
public bool IsNull { get { return !defined; } }public bool IsNull { get { return !defined; } }
public static DBInt operator +(DBInt x, DBInt y)public static DBInt operator +(DBInt x, DBInt y)
{...}{...}
public static implicit operator DBInt(int x) {...}public static implicit operator DBInt(int x) {...}
public static explicit operator int(DBInt x) {...}public static explicit operator int(DBInt x) {...}
}}
DBInt x = 123;DBInt x = 123;
DBInt y = DBInt.Null;DBInt y = DBInt.Null;
DBInt z = x + y;DBInt z = x + y;
58. Language FeaturesLanguage Features
VersioningVersioning
Overlooked in most languagesOverlooked in most languages
C++ and Java produce fragile base classesC++ and Java produce fragile base classes
Users unable to express versioning intentUsers unable to express versioning intent
C# allows intent to be expressedC# allows intent to be expressed
Methods are not virtual by defaultMethods are not virtual by default
C# keywords “virtual”, “override” andC# keywords “virtual”, “override” and
“new” provide context“new” provide context
C# can't guarantee versioningC# can't guarantee versioning
Can enable (e.g., explicit override)Can enable (e.g., explicit override)
Can encourage (e.g., smart defaults)Can encourage (e.g., smart defaults)
59. class Derived: Baseclass Derived: Base // version 1// version 1
{{
public virtual void Foo() {public virtual void Foo() {
Console.WriteLine("Derived.Foo");Console.WriteLine("Derived.Foo");
}}
}}
class Derived: Baseclass Derived: Base // version 2a// version 2a
{{
new public virtual void Foo() {new public virtual void Foo() {
Console.WriteLine("Derived.Foo");Console.WriteLine("Derived.Foo");
}}
}}
class Derived: Baseclass Derived: Base // version 2b// version 2b
{{
public override void Foo() {public override void Foo() {
base.Foo();base.Foo();
Console.WriteLine("Derived.Foo");Console.WriteLine("Derived.Foo");
}}
}}
class Baseclass Base // version 1// version 1
{{
}}
class Baseclass Base // version 2// version 2
{{
public virtual void Foo() {public virtual void Foo() {
Console.WriteLine("Base.Foo");Console.WriteLine("Base.Foo");
}}
}}
Language FeaturesLanguage Features
VersioningVersioning
60. Language FeaturesLanguage Features
Conditional CompilationConditional Compilation
#define, #undef#define, #undef
#if, #elif, #else, #endif#if, #elif, #else, #endif
Simple boolean logicSimple boolean logic
Conditional methodsConditional methods
public class Debugpublic class Debug
{{
[Conditional("Debug")][Conditional("Debug")]
public static void Assert(bool cond, String s) {public static void Assert(bool cond, String s) {
if (!cond) {if (!cond) {
throw new AssertionException(s);throw new AssertionException(s);
}}
}}
}}
61. Language FeaturesLanguage Features
Unsafe CodeUnsafe Code
COM integration, P/invoke cover most casesCOM integration, P/invoke cover most cases
Unsafe codeUnsafe code
Low-level code without leaving the boxLow-level code without leaving the box
Enables unsafe casts, pointer arithmeticEnables unsafe casts, pointer arithmetic
Declarative pinningDeclarative pinning
Fixed statementFixed statement
Basically “inline C”Basically “inline C”
unsafe void Foo() {unsafe void Foo() {
char* buf = stackalloc char[256];char* buf = stackalloc char[256];
for (char* p = buf; p < buf + 256; p++) *p = 0;for (char* p = buf; p < buf + 256; p++) *p = 0;
......
}}
62. Language FeaturesLanguage Features
Unsafe CodeUnsafe Code
class FileStream: Streamclass FileStream: Stream
{{
int handle;int handle;
publicpublic unsafeunsafe int Read(byte[] buffer, int index, intint Read(byte[] buffer, int index, int
count) {count) {
int n = 0;int n = 0;
fixedfixed (byte* p = buffer) {(byte* p = buffer) {
ReadFile(handle, p + index, count, &n, null);ReadFile(handle, p + index, count, &n, null);
}}
return n;return n;
}}
[[dllimportdllimport("kernel32", SetLastError=true)]("kernel32", SetLastError=true)]
static externstatic extern unsafeunsafe bool ReadFile(int hFile,bool ReadFile(int hFile,
void* lpBuffer, int nBytesToRead,void* lpBuffer, int nBytesToRead,
int* nBytesRead, Overlapped* lpOverlapped);int* nBytesRead, Overlapped* lpOverlapped);
}}
63. Language FeaturesLanguage Features
COM SupportCOM Support
.Net framework provides great.Net framework provides great
COM supportCOM support
TLBIMP imports existing COM classesTLBIMP imports existing COM classes
TLBEXP exports .NET typesTLBEXP exports .NET types
Most users will have aMost users will have a
seamless experienceseamless experience
64. Language FeaturesLanguage Features
COM SupportCOM Support
Sometimes you need more controlSometimes you need more control
Methods with complicated structuresMethods with complicated structures
as argumentsas arguments
Large TLB – only using a few classesLarge TLB – only using a few classes
System.Runtime.InteropservicesSystem.Runtime.Interopservices
COM object identificationCOM object identification
Parameter and return value marshallingParameter and return value marshalling
HRESULT behaviorHRESULT behavior
67. C# And CLI StandardizationC# And CLI Standardization
Work begun in September 2000Work begun in September 2000
Submitted to ECMA (www.ecma.ch)Submitted to ECMA (www.ecma.ch)
Active involvement by Intel, HP, IBM,Active involvement by Intel, HP, IBM,
Fujitsu, Plum Hall, …Fujitsu, Plum Hall, …
Since December 2001Since December 2001
““C# Language Specification”C# Language Specification”
““Common Language Infrastructure (CLI)”Common Language Infrastructure (CLI)”
This session will provide a complete overview of the C# language, starting with the traditional Hello World application to some of the innovative features of C# like value and reference types, boxing and unboxing, delegates, attributes and robust versioning. We’ll also give a brief introduction to the .NET Framework and the Common Language Runtime.
KEY MESSAGE: Session Prerequisites
SLIDE SCRIPT:
It will help a lot if the audience has previous experience with object oriented programming as we will discuss concepts like inheritance and performance implications of languages that treats everything as an object.
Visual Basic developers maybe will not get some of the points but this session will serve as a good starting point as well.
SLIDE TRANSISTION: what will be covered today
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: .NET Framework and C# Language
SLIDE SCRIPT:
SLIDE TRANSISTION: Agenda
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Agenda Slide
SLIDE SCRIPT:
As usual, we’ll start with the traditional Hello World. Then we’ll take a step back and explain the main concepts behind the .NET Framework and then drill down again in the C# Language
SLIDE TRANSISTION: Hello World
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Hello World is really simple in C#!
SLIDE SCRIPT:
The Hello World application is very simple in C#. Some key points:
In C# there is no global methods. Everything belongs to a class.
A method named Main is the entry point for a C# application. Note that Main is spelled with a capital “M”, which is different than C and C++. The reason is that for consistency, all method names start with a capital letter in the .NET Framework
The line using System; means that we’ll be accessing members of the System namespace. In a very rough comparison, a namespace could be translated to a Unit in Turbo Pascal/Delphi or a .LIB file in C/C++. So in the Hello World example, the class Console, which contains the method WriteLine belongs to the System namespace. We could avoid the “using” statement by writing the complete path of the method:System.Console.WriteLine(“Hello World”);
SLIDE TRANSISTION: Agenda
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Agenda Slide
SLIDE SCRIPT:
We’ll now give a brief introduction to the .NET Framework.
SLIDE TRANSISTION: Introduction to the .NET Framework
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
OPTIONAL SLIDE, USE IF AUDIENCE HAD NO PREVIOUS EXPOSURE TO .NET
KEY MESSAGE:
The .NET Framework is a complete set of technologies that makes it easy to create the next generation of applications. And VS.NET is the set of tools that takes advantage of this infrastructure.
SLIDE SCRIPT:
The .NET framework exposes numerous classes to the developer. These classes allow the development of rich client applications and Web based applications alike. In the above slide these classes have been divided into 4 areas.
ASP.NET provides the core Web infrastructure such as Web Forms for UI based development and Web Services for programmatic interface development,
User interface development on the Windows platform can be done using Windows Forms
ADO.NET and XML provide the functionality for data access.
Finally, the core base classes provide infrastructure services such as security, transaction management etc.
SLIDE TRANSISTION: Common Language Runtime
&lt;number&gt;
KEY MESSAGE: Common Language Runtime
SLIDE SCRIPT:
At the core of the .NET Framework is the Common Language Runtime which provides a managed environment for all languages. The Common Language Runtime is one of the key differentiators of the .NET Framework from everything else. For example, before the .NET Framework, each language had to implement services like memory management or object layout. This means that for anything but the simplest data types, some kind of conversion would definitely would be needed to, let’s say, use a piece of memory allocated in C++ in VB or Java. The Common Language Runtime eliminates these needs, it allows you to inherit a C# class in Visual Basic or COBOL.
Also it is important to note that the CLR is not platform specific, in fact, is part of our strategy to use the CLR to make it easy to develop the next generation of applications to other devices like cell phones or handhelds.
SLIDE TRANSISTION:
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE:So what is the .NET Framework?
SLIDE BUILDS: None
SLIDE SCRIPT:
If you think back to Visual Basic, VB had a framework. There were certain things available in a VB application. MsgBox, for example, was part of the VB runtime. Many of the features of the VB framework were only available from VB. You can think of MFC as another framework. You could use MFC to build 32 bit windows applications. Again these classes were only available to C++ developers.
Wouldn’t it be nice if you were using the same classes, and the same data types from VB and C++? Wouldn’t it be nice if you got equal performance from these languages? Wouldn’t it be nice if VB and C++ solutions packaged and deployed exactly the same way? Wouldn’t it be nice if you could use VB, or C++ as the coding language for your web pages?
This is what the .NET framework does for you, and more. You can think of .NET as a new runtime environment that all the languages use. So all the same classes are available to all the languages. This means that the languages are very interoperable. You can create a class in VB and inherit in in C++, or the new C# language. An Int32 is the same data type in VB, or C++, or C#.
When you compile your application, it doesn’t actually compile to machine code. It compiles to in intermediate language (MSIL). When you actually execute the code, it compiles it machine code for the platform it’s executing on.
.NET introduces another new concept; Assemblies. Assemblies take the place of DLLs and EXEs, with some important distinctions. DLL Assemblies never register in the registry, so you can have multiple, incompatible versions of assemblies on the same box at the same time. An application can use the version it needs.
In the past, process boundaries separated applications from each other. Process boundaries protect the memory space of one process from another. With .NET, applications pass through a verification process that insures that the code cannot access a memory address that would be invalid for that application, or fail in some way that would terminate the process. Once the code passes the verification, it’s considered “type-safe”. Type safe code does not need the operating system to protect it from other type safe code. The framework has already insured this. Therefore, several .NET application can run within the same process space, know as a Application Domain. This offers significant performance improvements over having a separate process for each application.
SLIDE TRANSISTION: Layers of the framework
ADDITIONAL INFORMATION FOR PRESENTER:
The Common Language Runtime is the centre of the .NET Framework. Think of the CLR as a massive set of standard services that are exposed to you as a developer. The idea behind the CLR is to take the pain away from development allowing you as a developer to get on with your job – “Solving business problems!”.
As a Microsoft developer you have no doubt been exposed to COM at some level or other. Although we all love the COM architecture, we must admit that life isn’t always straight forward in the COM world. For example, installation and the registry, aggregation, object lifetime etc. All of these issues (and many more) have been addressed in the .NET Framework.
For example, .NET Components don’t necessarily have to be written in a set language. It’s possible for one developer to write a .NET component in VB and then cerate a C# component that derives from the VB component. This is what is termed as ‘Cross Language Inheritance’ and in the COM world we would have had to resort to aggregation.
What about deployment? Installing COM classes is not always straight forward. Most developers in the past have fought numerous battles with the registry! Installing .NET components is much less complex. In fact more often than not installation of .NET based software packages will just require copying files to a location on the hard disk. As you read further into the subject of .NET you will come across the expression ‘xcopy deployment’. This is not a new technology developed by Microsoft, but a reference to our good old DOS friend ‘xcopy’!
In fact .NET goes to great lengths to make component based software development much easier and more productive. What if you could forget about reference counting (IUnknown), class objects, dll server entry points (DllGetClassObject, DllCanUnloadNow, etc) and type libraries? Well, you can. More on this later.
Finally, when writing .NET components your source code will not be compiled to native machine instructions, but instead to Microsoft’s Intermediate Language (MSIL). This MSIL code is compiled at runtime into native code. This process obviously opens up a wide audience of machine platforms.
KEY MESSAGE: Explain the process of converting source code to binary code
SLIDE BUILDS: None
SLIDE SCRIPT: Obviously before the IL code can be executed it must be converted into native binary instructions. Converted? Does this mean interpreted? NO! The IL code is compiled and not thrown away. This means that next time the code is requested it is already in the form of machine instructions and thus this mechanism in the log run is far more efficient than an interpreter for example.
The compilation is carried out by a JIT (Just In Time) compiler. Does the compiler compile all of the code in one go? The answer to this question is NO. If this approach was taken there would be a long delay during the applications initialisation, and realistically not all the code within the module will be required in one go. Instead, when the code is loaded a ‘stub’ is connected to each method. When a method is called via the stub the compiler generates the binary native code. This mechanism goes a long way to describing why the compiler is called a ‘JIT’ compiler.
Compiled code is only saved in the same process (run) of an application. And even then it&apos;s not guaranteed. we do what&apos;s called &quot;code-pitching&quot; which means we through away cold (or little used) JITed code if memory pressure requires it. We do persisted JITed code in the install time scenario.
The benefit for to this system is obviously portability. A couple of things to think about -
Let’s imagine you’ve built a managed component for the Intel Pentium III platform. It works fine. Later in the year Intel release a super new chip. When Microsoft release a new version of the JIT, it’s possible that this brand spanking new version of the JIT will have learned a few new tricks e.g. to make use of the new improved instruction set of the new Intel chip or new CPU registers!
And finally, Microsoft plan to offer a tool called PREJIT. This tool will compile your assemblies at install time into native code and save the resultant binary executable code to disk. When the assemblies are next loaded the binary code is already available thus improving startup time and execution speeds.
SLIDE TRANSISTION: Let us get down to writing code for .NET using Visual Studio.NET…
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: .NET Framework also provides a large number of services exposed through a set of classes available to all languages.
SLIDE SCRIPT:
.NET Framework also provides a very rich set of services exposed through a class library. From web applications to data access, network connectivity to XML support, everything is covered in the .NET Framework. Also the entire framework was designed to support the .NET Vision, which means the next generation of applications.
Microsoft believes that the next generation of web applications will not only allow users to browse, but also expose their functionality to other sites as well through what we call Web Services. The .NET Framework was designed from the ground up to support this kind of scenario where the web becomes a component of other solutions. Also we support a scenario where not only web sites take advantage of these rich services but smart applications running on different devices, from cell phones to PC’s, can also use Web Services.
SLIDE TRANSISTION: We’ll drill down a little bit into each of these key services in the next slide
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE:
SLIDE SCRIPT:
These are some of the key services provided by the .NET Framework:
ASP.NET: Super set of what developers already know as Active Server Pages, with some key advantages: since it runs inside the CLR, it support any language that runs in the CLR, expanding from VBScript and Jscript. Also it provides numerous new services, like cache management, cluster-ready session management, cookie-less sessions, browser version-based automatic code generation, among other things
Windows Forms: For rich Windows applications, there is this completely redesigned set of classes. So instead of having MFC and ATL for C++ and Visual Basic Forms for VB applications, all languages share a common Form model.
ADO.NET: Also an evolution of ADO, with much richer XML support. You can now bind to an XML document
Also, XML support is integrated in all layers of the .NET Framework
SLIDE TRANSISTION: Let’s go back to C# know that we know that not only we have a new language, but also a really cool set of new services that allows the programmer to be really productive
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Agenda again
SLIDE SCRIPT:
We’ll now explain why Microsoft decided to create a new language
SLIDE TRANSISTION:
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Main ideas behind C#: component support, everything is an object, robust and durable software and preserve investments
SLIDE SCRIPT:
First of all, C# was designed from the ground up to support components concepts like events, methods and properties.
Second, everything is an object, which allows us to do some really clean designs.
Third, it was designed to make it easy to create robust and maintainable software
And finally, it should be able to integrate easily with everything that already exists, preserving your investment.
SLIDE TRANSISTION: Let’s start with component support.
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: C# is a Component Oriented Language
SLIDE SCRIPT:
First of all, C# was designed from the ground up to support components. It is the first language in the C/C++ family to support the concepts of components. But what defines a component? Basically it is the not only classes and methods, but also properties and events. It is not that is not possible to do component based development in C++, but you must rely usually on coding conventions like to define a property, let’s name this method as GetSomething and SetSomething. If you want to support events then it means that you need to implement this and that interface. In C#, the concept of properties, methods and events are all native. In fact, C++ only supports the concept of methods. Just as an analogy, it is not impossible to write object oriented programs in C, it is only harder than in C++. The same applies to component based development in C++ vs. C#.
Also when you move to component based development you have to think in a number of other factors like separate files to describe my components, like header files in C++, IDL to describe component interfaces and so on. In C# none of these are needed since it has built-in support for these concepts, enabling what we call one stop programming, so everything can be described in the source code, instead of requiring separate files.
SLIDE TRANSISTION: Everything is an Object
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Everything is an Object
SLIDE SCRIPT:
There are two different schools here: the purists like Smalltalk where everything is an object and C++ or Java, where primitive types are treated differently for performance reasons. Typically, when everything is an object, it means that every time that you do a simple operation like adding to numbers, it will incur on a heap allocation, which is quite expensive from the CPU standpoint compared to a stack allocated piece of memory. On the other hand, when languages threat primitive types as magic types, it means that if you implement a generic class, like a collection or array, it is not truly generic, because you either have to implement one version for each primitive type or you have to write wrapper classes to each of the primitive types so they can behave as an object.
In C#, it is possible if you declare a primitive type, it is created on the stack, with all performance benefits that this brings. However it is possible to assign an integer to an object, and the runtime will automatically allocate the memory on the heap to accommodate the integer and threat it as an object. This happens automatically without requiring the programmer to write an wrapper class.
Just as a side note for VB programmers: you can compare a stack allocation to a stack of paper where you can only write to the top page. As soon as you enter a function or sub you get a new page and you’re done (exit the function) you just throw away the top page. Let’s say that garbage management is really simple in this scenario.
Heap allocation is like having multiple pages at your disposal and also they don’t necessary vanish when your function ends. You can imagine that it is a lot more complex, because a piece of data on page 2 could be disposed, but another piece on the same page could still be needed by a different part of the code. In other words, a lot more management is necessary. Did you ever thought about what your boss do? It manages a heap while you do the real work using a stack…
SLIDE TRANSISTION: Robust software
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Prevent common mistakes from other languages
SLIDE SCRIPT:
C# has a lot of features to make it easier to create robust software.
Every C++ programmer knows how easy is to have a pointer to an object that was already de-allocated. C# provides automatically garbage collection through the Common Language Runtime.
Also, if you think about how error were handle in most of the code today, they’re mostly based on checking return codes. Exceptions provides a way to write a less code while at the same time providing a much more robust error handling mechanism. Not only exception handling is implemented in the language but it is also a inherent part of the .NET Framework
Another point is that all variables are automatically initialised and it is impossible to do unsafe casts.
Finally, C# is one of the first languages that provides a versioning semantics to easily support old and new clients.
SLIDE TRANSISTION: Preserving your investment
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Leverage C++ knowledge, interoperability and rich class library
SLIDE SCRIPT:
First of all, since C# was based on C++, C++ programmers will adapt really quick.
Second, interoperability is a key theme in the .NET Framework. So it is really easy to integrate C# code with existing applications
Finally, the .NET Framework provides a very, very rich set of services that will make developers really productive.
SLIDE TRANSISTION: Agenda again…
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Leverage C++ knowledge, interoperability and rich class library
SLIDE SCRIPT:
First of all, since C# was based on C++, C++ programmers will adapt really quick.
Second, interoperability is a key theme in the .NET Framework. So it is really easy to integrate C# code with existing applications
Finally, the .NET Framework provides a very, very rich set of services that will make developers really productive.
SLIDE TRANSISTION: Agenda again…
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE: Let’s drill down into the language features of C# language now…
SLIDE SCRIPT:
SLIDE TRANSISTION: Program Structure
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
The typical C# program is made of a namespace, with one or more type declarations, with each of these types (classes, structs, etc…) containing one or more methods, properties, events, etc.
As we mentioned before, C# doesn’t need header files and also there is no order dependences, so you can safely move one class from one file or another, or the order that you reference namespaces doesn’t affect the behaviour of your code.
SLIDE TRANSISTION: Program Structure example
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
This is a typical C# class with two methods Push and Pop, declared in a namespace (System.Collections). This is the typical C# program structure.
SLIDE TRANSISTION: Value types and Reference Types
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Value types and Reference Types
SLIDE SCRIPT:
In C# you have Value types that directly hold the data on the stack and reference types that keeps a reference on the stack, but allocates the real memory on the heap.
SLIDE TRANSISTION: Examples of Value and Reference types
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Examples of Value types and Reference types
SLIDE SCRIPT:
Enums and structs are stack allocated. Classes are heap allocated. But both structs and classes inherits from object, so you can simply attribute a struct to an object and threat it as a reference type.
SLIDE TRANSISTION: Predefined Types
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Even primitive types actually belongs to a namespace. Actually primitive types are just predefined aliases for system provided types. For example int is just an alias to System.Int32 struct in the .NET Framework.
SLIDE TRANSISTION: Classes
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Classes in C# allow single inheritance and multiple interface inheritance. Each class can contain methods, properties, events, indexers, constants, constructors, destructors, operators and members can be static (can be accessed without an object instance) or instance member (require you to have a reference to an object first)
Also, the access can be controlled in four different levels: public (everyone can access), protected (only inherited members can access), private (only members of the class can access) and internal (anyone on the same EXE or DLL can access)
SLIDE TRANSISTION: Structs
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
To provide a really high performance object type, C# provides structs, which are stack allocated. They’re ideal for small objects and are really fast since they don’t depend on dynamic memory allocation and the garbage collector. It is also important to notice that it is not possible to inherit from an struct.
SLIDE TRANSISTION: classes and structs compared
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Again, comparing classes and structs, it is the memory layout of a struct is just a direct representation of its members directly on the stack. On a class, a reference is stored on the stack, while the object itself is stored in the heap.
SLIDE TRANSISTION: Intefaces
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
In scenarios where completely different objects need to support some kind of shared functionality like, let’s say, persist to XML, classes can implement interfaces that make then compatible with even if they don’t share the same base class. This provides most of the benefits of multiple class inheritance without the nasty side-effects that this usually brings.
SLIDE TRANSISTION: Enums
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Enums in C# are strongly typed, which means that you can’t assign a int enum to a long, or vice versa, avoiding some typical conversion mistakes.
SLIDE TRANSISTION: Delegates
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Delegates are the base of event support in C#
SLIDE SCRIPT:
Delegates is equivalent to a function pointer to a method. This is the mechanism used to implement event in the frameworks. In the example we are declaring two delegates, which mean two pointers types that can only accept addresses to functions with a specific method signature. In the first example, the pointer could only accept an address from a function that returns void and receives two integers. In the second example is a delegate to a function that returns double and receives a double as a parameter.
In the last two lines, we’re getting the address of function Math.Sin and attributing it to func, and then calling it through the pointer func.
SLIDE TRANSISTION: Unfiied Type System
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Everything is an object
SLIDE SCRIPT:
Everything inherits from object, even if they’re primitive types, structs or classes.
SLIDE TRANSISTION: Boxing and Unboxing
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Boxing and Unboxing is one of the key innovations of C# language. Instead of requiring the programmer to write wrapper code to convert from stack based memory to heap memory, you just need to assign a value type to an object and C# takes care of allocating the memory in the heap and generating a copy of that on the heap. When you attribute the object to a stack based int, the value is converted to the stack again. This process is what we call Boxing and Unboxing.
SLIDE TRANSISTION: More on Unified Type System
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Main benefits of the Unified Type System:
No need of wrapper code to use base types in collections or arrays
No Variants anymore
SLIDE TRANSISTION: Component Development
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: What defines a component
SLIDE SCRIPT:
A component is a class with some twists like properties and events in addition to methods. Also in order to better support IDE’s we need to provide a mechanism to store metadata as well, like initial value of properties and enough type information to provide features like Intellisense.
Most of the other languages resort to adding external files like header files, IDL to address these problems. C# has built in support.
SLIDE TRANSISTION: Properties
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: How properties are implemented
SLIDE SCRIPT:
C# has a specific syntax to declare properties and how the get and set operations will be performed. To use, on the other hand, is just like a standard variable as you can see in the example.
SLIDE TRANSISTION: Indexers
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Indexers is an array property. It can be exactly like a property but you control the access to each element of the array.
SLIDE TRANSISTION: events
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE: Events are built into C#
SLIDE SCRIPT:
As we mentioned before, delegates are method signatures. So in order to implement an event in a class, first we define a this method signature, then we declare the event itself that will call methods of this specific method signature (public event EventHandler Click;) and finally we fire the event by calling the event (if (Click != null) Click(this, e); // Fires the event)
SLIDE TRANSISTION: Handling the event
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
From the component user perspective, an event is just like an property that accept a method pointer. So you just pass the method address that will handle the event and when the event occurs, the component will call your method
SLIDE TRANSISTION: Event Demo
ADDITIONAL INFORMATION FOR PRESENTER:
KEY MESSAGE:
SLIDE SCRIPT:
SLIDE TRANSISTION: Attributes
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
This is another innovation of C#. Every language, sooner or later needs to add more information in order to produce a working application. The reason for this varies from, let’s say, someone that decided that every class will now include documentation in a specific format to CORBA specific marshalling requirements. The solutions range from adding new keywords to the language or using external files like IDL or resource files.
SLIDE TRANSISTION: C# Attributes as a solutions
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
C# attributes allows you to associate metadata to any class or method. Even better you can define a new attribute by just declaring a new class that inherits from System.Atributes.
SLIDE TRANSISTION: Attributes explained.
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Since attribute values are stored with the generated code and can be examined by the code in run-time through a mechanism called reflection, you can infinitely add new attributes that will extend the functionality of your C# code. So just as an example, as a CORBA vendo, instead of having to create CORBA wrappers and utilities to write marshalling code, you can define a set of attributes that will instruct the CORBA broker how to marshal the data, also this could be applied to do add information on how to do object to relational database mapping or XML persistence.
SLIDE TRANSISTION: Attribute demo
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
SLIDE TRANSISTION: XML Comments
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Also the compiler has some features that allows you to keep the documentation as close as possible to the code. This will improve the change that your documentation will be kept up to date.
SLIDE TRANSISTION: Let’s see a demo of XML comments
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
SLIDE TRANSISTION: Statements and expressions
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
In the Statements and Expressions area C# is just like C++ with some key differences to improve code robustness. Other than solving the old assignment problem in if statements, goto usage is limited to safer scenarios and switch statements require break between each options avoiding the infamous fall through bug.
Also C# has a foreach statement to iterate through arrays and collections
SLIDE TRANSISTION: foreach
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
No need to do loops with explicit bounds checking. Just use foreach.
SLIDE TRANSISTION:
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Using parameter arrays, you can have type safe “printf” style methods, since everything is guaranteed to be an object.
SLIDE TRANSISTION:
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Just like C++, C# supports operator overloading. For VB developers: this mean that you can create a class that represents an Complex number and define what the operator + means for this class, for example.
SLIDE TRANSISTION: Operator overloading example
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Defining a new type called DBInt, which could be a integer that supports the concepts of NULLs to be compatible with database types. At the same time we support the operator + by overloading this operator so we can do operations like in the second box.
SLIDE TRANSISTION: versioning
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
One of the biggest problems in object oriented languages is how to handle versioning in base classes. This problem is so common that even has a name in OO circles: fragile base class. The problem is that in most languages there is no way to explicitly express the intent on what should happen when a base class change.
C# on the other hand, provide exact semantics about how the base class versioning should happen.
SLIDE TRANSISTION: Versioning example
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Let’s say that we have a base class that doesn’t do nothing.
BUILD: Then a user of this class inherited this class and create a method named Foo()
BUILD: Then the creator of the original base class realizes how Foo-ness is important and decided to implement that in the base class. Then we have a problem. How should this behave? Should the clients keep calling Derived.Foo or Base.Foo. In C# is guaranteed that Derived.Foo will be the one being called because it will most likely preserve the behaviour expected by the client. However the compiler will issue an warning saying that method Base.Foo was hid.
BUILD: to suppress the warning, the programmer can use the keyword new, and explicitly hide the method Base.Foo.
BUILD: Or if he can just override as any virtual method.
SLIDE TRANSISTION: Conditional Compilation
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Compiler directives are supported just like in C++ with a notable exception of Macros. The reason is that macros can change the behavior of the code just by changing a define. It also makes debugger really harder and also makes a lot more difficult to make proper optimizations.
However, there is a attribute called Conditional that can be used to suppress methods based on a define. This is how a type-safe Assert is implemented in C# without macros.
SLIDE TRANSISTION: Unsafe code
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
If you need to do some real low level memory manipulation, you can declare a method unsafe and then you have access to full C pointer syntax. You can think of unsafe methods as inline C.
SLIDE TRANSISTION: Unsafe example
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
Just declare the unsafe keyword and you can do full memory manipulation
SLIDE TRANSISTION: COM support
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
This is one are of great confusion among users. Gartner Group says that COM is dead. This is not true. If we’re talking about COM as a method to interoperate between languages, then, of course inside the Common Language Runtime we have much better means to do so. However, COM accessing existing COM components from .NET applications is almost seamless. Also COM+ Services like transactions are here to stay, they’re integral part of the .NET Strategy. In fact, to use COM+ Transactions, you just need to add an attribute to your class.
To use a COM component from C#, just use TLBIMP to create a proxy class and you’re ready to go.
SLIDE TRANSISTION: More COM Support
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
If you need more control you can access the namespace System.Runtime.Interopservices which provide a complete set of COM services.
SLIDE TRANSISTION: Calling a COM component from C# demo
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
SLIDE TRANSISTION:
ADDITIONAL INFORMATION FOR PRESENTER:
&lt;number&gt;
KEY MESSAGE:
SLIDE SCRIPT:
SLIDE TRANSISTION:
ADDITIONAL INFORMATION FOR PRESENTER: