Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

72
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    218
  • download

    0

Transcript of Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Page 1: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.
Page 2: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Introduction to C#Introduction to C#

Raimonds RudmanisRaimonds RudmanisSenior ConsultantSenior ConsultantMicrosoft Microsoft BalticBaltic

Page 3: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Session PrerequisitesSession Prerequisites

This session assumes that you This session assumes that you understand the fundamentals ofunderstand the fundamentals of Object oriented programming Object oriented programming

This is a Level 200 SessionThis is a Level 200 Session

Page 4: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

What Will Be Covered TodayWhat Will Be Covered Today

Brief introduction to Brief introduction to the .NET frameworkthe .NET framework

C# language overviewC# language overview

Page 5: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

AgendaAgenda

Hello WorldHello World The .NET FrameworkThe .NET Framework Design Goals of C#Design Goals of C# Language FeaturesLanguage Features

Page 6: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Hello WorldHello WorldDEMO 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"); }}}}

Page 7: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

AgendaAgenda

Hello WorldHello World The .NET FrameworkThe .NET Framework Design Goals of C#Design Goals of C# Language FeaturesLanguage Features

Page 8: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

The .NET FrameworkThe .NET FrameworkOverviewOverview

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#

Visu

al Stu

dio

.NE

TV

isual S

tud

io.N

ET

ASP.NET: Web ServicesASP.NET: Web ServicesAnd Web FormsAnd Web Forms

JScriptJScript ……

WindowsWindowsformsforms

Page 9: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

The .NET FrameworkThe .NET FrameworkCommon 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#V

isual S

tud

io.N

ET

Visu

al Stu

dio

.NE

T

ASP.NET: Web ServicesASP.NET: Web Servicesand Web Formsand Web Forms

JScriptJScript ……

WindowsWindowsFormsForms

Page 10: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

New Runtime Environment – Common New 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 Machine Runtime Controls Compilation to Machine

CodeCode AssembliesAssemblies Application DomainsApplication Domains

The .NET FrameworkThe .NET FrameworkCommon Language RuntimeCommon Language Runtime

Page 11: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

The .NET FrameworkThe .NET FrameworkCommon 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

Page 12: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

.NET Framework and CLR .NET Framework and CLR CLR Execution ModelCLR Execution Model

VBVBSource Source codecode

CompilerCompiler

C++C++C#C#

CompilerCompilerCompilerCompiler

AssemblyAssemblyIL CodeIL Code

AssemblyAssemblyIL CodeIL Code

AssemblyAssemblyIL CodeIL Code

Operating System ServicesOperating System Services

Common Language RuntimeCommon Language Runtime

JIT CompilerJIT Compiler

Native CodeNative Code

ManagedManagedcodecode

UnmanagedUnmanagedComponentComponent

Page 13: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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#V

isual S

tud

io.N

ET

Visu

al Stu

dio

.NE

T

ASP.NET: Web ServicesASP.NET: Web Servicesand Web Formsand Web Forms

JScriptJScript ……

WindowsWindowsFormsForms

Page 14: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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 Forms Web Forms Web ServicesWeb Services

WindowsWindows®® Forms Forms 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

Page 15: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

AgendaAgenda

Hello WorldHello World The .NET FrameworkThe .NET Framework Design Goals of C#Design Goals of C# Language FeaturesLanguage Features

Page 16: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Design Goals of C#Design Goals of C#The Big IdeasThe Big Ideas

The first The first “C“Component omponent OOrientedriented”” language in the C/C++ familylanguage in the C/C++ family

Everything really is an objectEverything really is an object Next generation robust and Next generation robust and

durable softwaredurable software Preserving your investmentPreserving your investment

Page 17: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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 No No external files like external files like header files, IDL, etc.header files, IDL, etc. Can be embedded in ASP pagesCan be embedded in ASP pages

Page 18: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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 are Smalltalk, 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

Page 19: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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 all Pervasive versioning considerations in all

aspects of language designaspects of language design

Page 20: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Design Goals of C#Design Goals of C# Preserving Your InvestmentPreserving Your Investment C++ HeritageC++ Heritage

Namespaces, Namespaces, enums, enums, pointers (in unsafe pointers (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

Page 21: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Design Goals of C#Design Goals of C# InteroperabilityInteroperability

C#C#

VB.NETVB.NET

MC++MC++

JScript JScript

... ...

.NET Languages.NET Languages

COMCOMOLE AutomationOLE Automation

XML/SOAPXML/SOAP

Dynamic Link LibrariesDynamic Link Libraries

P/Invoke and unsafe codeP/Invoke and unsafe code

Page 22: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

AgendaAgenda

Hello WorldHello World The .NET FrameworkThe .NET Framework Design Goals of C#Design Goals of C# Language FeaturesLanguage Features

Page 23: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesProgram 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

Page 24: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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;

}}

}}

}}

Page 25: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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"

Page 26: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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, struct Point { int x,

y; }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[] a = new string[10];string[10];

DelegatesDelegates delegate void delegate void Empty();Empty();

Page 27: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage Features Predefined TypesPredefined Types

C# predefined typesC# predefined types ReferenceReference object, stringobject, string SignedSigned sbyte, short, int, sbyte, short, int,

longlong Unsigned Unsigned byte, ushort, uint, byte, ushort, uint,

ulongulong CharacterCharacter charchar Floating-pointFloating-point float, double, float, double,

decimaldecimal 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

Page 28: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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

Page 29: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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

Page 30: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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

2020spsp

cpcp

1010

2020

CPointCPoint

Page 31: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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) {...}}}

Page 32: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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,}}

Page 33: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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);

Page 34: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesUnified Type SystemUnified Type System

Everything is an objectEverything is an object All types ultimately inherit from objectAll types ultimately inherit from object Any piece of data can be stored, Any piece of data can be stored,

transported, and manipulated with no transported, and manipulated with no extra workextra work

StreamStream

MemoryStreamMemoryStream FileStreamFileStream

HashtableHashtable doubledoubleintint

objectobject

Page 35: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesUnified 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

Page 36: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesUnified 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" );

Page 37: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesComponent 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 and Components are easy to build and to consumeto consume

Page 38: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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;

Page 39: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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[int public 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 = new ListBox listBox = new ListBox();ListBox();listBox[0] = "hello";listBox[0] = "hello";Console.WriteLine(listBox[0]);Console.WriteLine(listBox[0]);

Page 40: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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); } }}}

Page 41: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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"); }}}}

Page 42: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesDEMO 2: Creating an Event HandlerDEMO 2: Creating an Event Handler Define an Event Handler for a button in a Define an Event Handler for a button in a

Windows Forms applicationWindows Forms application

Page 43: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage Features AttributesAttributes

Associate information with types Associate 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

Page 44: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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 {...}

Page 45: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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…

Page 46: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

What Is A Web Service?What Is A Web Service?

HTML = user-to-machineHTML = user-to-machineXML/SOAP = machine-to-machineXML/SOAP = machine-to-machineLeveraging 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

Page 47: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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

Web Web ServiceService

WebWebService Service

ConsumerConsumer

UDDIUDDI

Find a ServiceFind a Servicehttp://www.uddi.orghttp://www.uddi.org

Link to DISCO or WSDL documentLink to DISCO or WSDL document

Page 48: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Web Services With .NETWeb Services With .NET

ProgramsPrograms

ObjectsObjects

ClassesClasses

MethodsMethods

CallsCalls

WebWeb

XMLXML

XSDXSD

WSDLWSDL

SOAPSOAP

DataData

SchemaSchema

ServicesServices

InvocationInvocation

ApplicationApplicationConceptsConcepts

The .NET framework providesThe .NET framework providesa bi-directional mappinga bi-directional mapping

Page 49: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Web Services With .NETWeb Services With .NETpublic 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>

Page 50: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesDEMO 3: AttributesDEMO 3: Attributes Create a Web service by using the Create a Web service by using the

[[WWebebMMethod] attributeethod] attribute

Page 51: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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) { ...... }}}}

Page 52: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesDEMO 4: XML CommentsDEMO 4: XML Comments Show how the compiler can auto generate Show how the compiler can auto generate

documentation from the source code using documentation from the source code using XML commentsXML comments

Page 53: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesStatements 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 and Checked and

uncheckeduncheckedstatementsstatements

Expression Expression statements statements must do workmust do work

void Foo() {void Foo() {i == 1;i == 1; // error// errori + 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 ) // errorerrorif ( i>0 )if ( i>0 )

FileClass file;FileClass file;

if ( file = OpenFile() ) // if ( file = OpenFile() ) // errorerrorif ( (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 shortstatic short y = 32767;static short y = 32767;

try try {{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:

Page 54: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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);}}

Page 55: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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);

Page 56: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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…

Page 57: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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;

Page 58: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage Features VersioningVersioning

Overlooked in most languagesOverlooked in most languages C++ and Java produce fragile base classes C++ 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” and C# 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)

Page 59: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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 Base class 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

Page 60: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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); }} }}}}

Page 61: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

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; ......}}

Page 62: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage Features Unsafe CodeUnsafe Code

class FileStream: Streamclass FileStream: Stream{{ int handle;int handle;

public public unsafeunsafe int Read(byte[] buffer, int index, int int 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 extern static 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);}}

Page 63: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesCOM SupportCOM Support

.Net framework provides great .Net framework provides great COM support COM support TLBIMP imports existing COM classesTLBIMP imports existing COM classes TLBEXP exports .NET types TLBEXP exports .NET types

Most users will have a Most users will have a seamless experienceseamless experience

Page 64: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage FeaturesCOM SupportCOM Support

Sometimes you need more control Sometimes you need more control Methods with complicated structures Methods 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

Page 65: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage Features DEMO 5: COM and C#DEMO 5: COM and C#Call a COM component from C#Call a COM component from C#

Page 66: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Language FeaturesLanguage Features DEMO 6: Visual Studio .NETDEMO 6: Visual Studio .NETWindows programming with C#Windows programming with C#

Page 67: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

C# And CLI StandardizationC# And CLI Standardization

Work begun in September 2000Work begun in September 2000Submitted 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)”

Page 68: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

C# BooksC# Books

Page 70: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

More ResourcesMore Resources

http://msdn.microsoft.com/http://msdn.microsoft.com/ C# language specificationC# language specification C# newsgroupsC# newsgroups

microsoft.public.dotnet.languages.csharpmicrosoft.public.dotnet.languages.csharp

Page 71: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

Questions?Questions?

Page 72: Introduction to C# Raimonds Rudmanis Senior Consultant Microsoft Baltic.

© 2001 Microsoft Corporation. All rights reserved.© 2001 Microsoft Corporation. All rights reserved.