Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Introduction to C#Introduction to C#
Raimonds RudmanisRaimonds Rudmanis
Senior ConsultantSenior Consultant
MicrosoftMicros...
Session PrerequisitesSession Prerequisites
 This session assumes that youThis session assumes that you
understand the fun...
What Will Be Covered TodayWhat Will Be Covered Today
 Brief introduction to theBrief introduction to the
.NET framework.N...
AgendaAgenda
 Hello WorldHello World
 The .NET FrameworkThe .NET Framework
 Design Goals of C#Design Goals of C#
 Lang...
Hello WorldHello World
DEMO 1: Hello WorldDEMO 1: Hello World
using System;using System;
class Helloclass Hello
{{
static ...
AgendaAgenda
 Hello WorldHello World
 The .NET FrameworkThe .NET Framework
 Design Goals of C#Design Goals of C#
 Lang...
The .NET FrameworkThe .NET Framework
OverviewOverview
Base Class LibraryBase Class Library
Common Language SpecificationCo...
The .NET FrameworkThe .NET Framework
Common Language RuntimeCommon Language Runtime
Base Class LibraryBase Class Library
C...
 New Runtime Environment – CommonNew Runtime Environment – Common
Language RuntimeLanguage Runtime
 Language Interoperab...
The .NET FrameworkThe .NET Framework
Common Language RuntimeCommon Language Runtime
 Simplified developmentSimplified dev...
.NET Framework and CLR.NET Framework and CLR
CLR Execution ModelCLR Execution Model
VBVBSourceSource
codecode
CompilerComp...
The .NET FrameworkThe .NET Framework
.NET Framework Services.NET Framework Services
Base Class LibraryBase Class Library
C...
The .NET FrameworkThe .NET Framework
.NET Framework Services.NET Framework Services
 ASP.NETASP.NET
 Separation of code ...
AgendaAgenda
 Hello WorldHello World
 The .NET FrameworkThe .NET Framework
 Design Goals of C#Design Goals of C#
 Lang...
Design Goals of C#Design Goals of C#
The Big IdeasThe Big Ideas
 The firstThe first “C“Componentomponent OOrientedriented...
Design Goals of C#Design Goals of C#
A Component Oriented LanguageA Component Oriented Language
 C# is the first “Compone...
Design Goals of C#Design Goals of C#
Everything Really Is an ObjectEverything Really Is an Object
 Traditional viewsTradi...
Design Goals of C#Design Goals of C#
Robust and Durable SoftwareRobust and Durable Software
 Garbage collectionGarbage co...
Design Goals of C#Design Goals of C#
Preserving Your InvestmentPreserving Your Investment
 C++ HeritageC++ Heritage
 Nam...
Design Goals of C#Design Goals of C#
InteroperabilityInteroperability
C#C#
VB.NETVB.NET
MC++MC++
JScriptJScript
......
.NE...
AgendaAgenda
 Hello WorldHello World
 The .NET FrameworkThe .NET Framework
 Design Goals of C#Design Goals of C#
 Lang...
Language FeaturesLanguage Features
Program StructureProgram Structure
 NamespacesNamespaces
 Contain types and other nam...
Language FeaturesLanguage Features
Program StructureProgram Structure
using System;using System;
namespace System.Collecti...
Language FeaturesLanguage Features
Type SystemType System
 Value typesValue types
 Directly contain dataDirectly contain...
Language FeaturesLanguage Features
Type SystemType System
 Value typesValue types
 PrimitivesPrimitives int i;int i;
 E...
Language FeaturesLanguage Features
Predefined TypesPredefined Types
 C# predefined typesC# predefined types
 ReferenceRe...
Language FeaturesLanguage Features
ClassesClasses
 Single inheritanceSingle inheritance
 Multiple interface implementati...
Language FeaturesLanguage Features
StructsStructs
 Like classes, exceptLike classes, except
 Stored in-line, not heap al...
Language FeaturesLanguage Features
Classes and StructsClasses and Structs
struct SPoint { int x, y; ... }struct SPoint { i...
Language FeaturesLanguage Features
InterfacesInterfaces
 Multiple inheritanceMultiple inheritance
 Can contain methods, ...
Language FeaturesLanguage Features
EnumsEnums
 Strongly typedStrongly typed
 No implicit conversions to/from intNo impli...
Language FeaturesLanguage Features
DelegatesDelegates
 Object oriented function pointersObject oriented function pointers...
Language FeaturesLanguage Features
Unified Type SystemUnified Type System
 Everything is an objectEverything is an object...
Language FeaturesLanguage Features
Unified Type SystemUnified Type System
 BoxingBoxing
 Allocates box, copies value int...
Language FeaturesLanguage Features
Unified Type SystemUnified Type System
 BenefitsBenefits
 Eliminates “wrapper classes...
Language FeaturesLanguage Features
Component DevelopmentComponent Development
 What defines a component?What defines a co...
Language FeaturesLanguage Features
PropertiesProperties
 Properties Are “Smart Fields”Properties Are “Smart Fields”
 Nat...
Language FeaturesLanguage Features
IndexersIndexers
 Indexers are “smart arrays”Indexers are “smart arrays”
 Can be over...
Language FeaturesLanguage Features
Creating and Firing an EventCreating and Firing an Event
 Define the Event signatureDe...
Language FeaturesLanguage Features
Handling an EventHandling an Event
 Define and register Event HandlerDefine and regist...
Language FeaturesLanguage Features
DEMO 2: Creating an Event HandlerDEMO 2: Creating an Event Handler
 Define an Event Ha...
Language FeaturesLanguage Features
AttributesAttributes
 Associate information with typesAssociate information with types...
Language FeaturesLanguage Features
AttributesAttributes
public class OrderProcessorpublic class OrderProcessor
{{
[WebMeth...
Language FeaturesLanguage Features
AttributesAttributes
 Attributes can beAttributes can be
 Attached to types and membe...
What Is A Web Service?What Is A Web Service?
 HTML = user-to-machineHTML = user-to-machine
 XML/SOAP = machine-to-machin...
DiscoveryDiscovery
Let’s talk (SOAP)Let’s talk (SOAP)
How Does It Work?How Does It Work?
http://myservice.comhttp://myserv...
Web Services With .NETWeb Services With .NET
ProgramsPrograms
ObjectsObjects
ClassesClasses
MethodsMethods
CallsCalls
WebW...
Web Services With .NETWeb Services With .NET
public class OrderProcessorpublic class OrderProcessor
{{
public void SubmitO...
Language FeaturesLanguage Features
DEMO 3: AttributesDEMO 3: Attributes
 Create a Web service by using theCreate a Web se...
Language FeaturesLanguage Features
XML CommentsXML Comments
class XmlElementclass XmlElement
{{
/// <summary>/// <summary>...
Language FeaturesLanguage Features
DEMO 4: XML CommentsDEMO 4: XML Comments
 Show how the compiler can auto generateShow ...
Language FeaturesLanguage Features
Statements and ExpressionsStatements and Expressions
 High C++ fidelityHigh C++ fideli...
Language FeaturesLanguage Features
For Each StatementFor Each Statement
 Iteration of arraysIteration of arrays
 Iterati...
Language FeaturesLanguage Features
Parameter ArraysParameter Arrays
 Can write “printf” style methodsCan write “printf” s...
Language FeaturesLanguage Features
Operator OverloadingOperator Overloading
 First class user-defined data typesFirst cla...
Language FeaturesLanguage Features
Operator OverloadingOperator Overloading
public struct DBIntpublic struct DBInt
{{
publ...
Language FeaturesLanguage Features
VersioningVersioning
 Overlooked in most languagesOverlooked in most languages
 C++ a...
class Derived: Baseclass Derived: Base // version 1// version 1
{{
public virtual void Foo() {public virtual void Foo() {
...
Language FeaturesLanguage Features
Conditional CompilationConditional Compilation
 #define, #undef#define, #undef
 #if, ...
Language FeaturesLanguage Features
Unsafe CodeUnsafe Code
 COM integration, P/invoke cover most casesCOM integration, P/i...
Language FeaturesLanguage Features
Unsafe CodeUnsafe Code
class FileStream: Streamclass FileStream: Stream
{{
int handle;i...
Language FeaturesLanguage Features
COM SupportCOM Support
 .Net framework provides great.Net framework provides great
COM...
Language FeaturesLanguage Features
COM SupportCOM Support
 Sometimes you need more controlSometimes you need more control...
Language FeaturesLanguage Features
DEMO 5: COM and C#DEMO 5: COM and C#
Call a COM component from C#Call a COM component f...
Language FeaturesLanguage Features
DEMO 6: Visual Studio .NETDEMO 6: Visual Studio .NET
Windows programming with C#Windows...
C# And CLI StandardizationC# And CLI Standardization
 Work begun in September 2000Work begun in September 2000
 Submitte...
C# BooksC# Books
C# CustomersC# Customers
More ResourcesMore Resources
 http://msdn.microsoft.com/http://msdn.microsoft.com/
 C# language specificationC# language...
Questions?Questions?
© 2001 Microsoft Corporation. All rights reserved.© 2001 Microsoft Corporation. All rights reserved.
Introduction to c_sharp
Upcoming SlideShare
Loading in …5
×

Introduction to c_sharp

138 views

Published on

Visual Studio Dot Net Tutorial Slide

Published in: Education
  • Be the first to comment

  • Be the first to like this

Introduction to c_sharp

  1. 1. Introduction to C#Introduction to C# Raimonds RudmanisRaimonds Rudmanis Senior ConsultantSenior Consultant MicrosoftMicrosoft BalticBaltic
  2. 2. 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
  3. 3. 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
  4. 4. AgendaAgenda  Hello WorldHello World  The .NET FrameworkThe .NET Framework  Design Goals of C#Design Goals of C#  Language FeaturesLanguage Features
  5. 5. 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"); }} }}
  6. 6. AgendaAgenda  Hello WorldHello World  The .NET FrameworkThe .NET Framework  Design Goals of C#Design Goals of C#  Language FeaturesLanguage Features
  7. 7. 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
  8. 8. 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
  9. 9.  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
  10. 10. 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
  11. 11. .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
  12. 12. 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
  13. 13. 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
  14. 14. AgendaAgenda  Hello WorldHello World  The .NET FrameworkThe .NET Framework  Design Goals of C#Design Goals of C#  Language FeaturesLanguage Features
  15. 15. 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
  16. 16. 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
  17. 17. 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
  18. 18. 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
  19. 19. 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
  20. 20. 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
  21. 21. AgendaAgenda  Hello WorldHello World  The .NET FrameworkThe .NET Framework  Design Goals of C#Design Goals of C#  Language FeaturesLanguage Features
  22. 22. 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
  23. 23. 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; }} }} }}
  24. 24. 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"
  25. 25. 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();
  26. 26. 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
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. 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) {...} }}
  31. 31. 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, }}
  32. 32. 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);
  33. 33. 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
  34. 34. 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
  35. 35. 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" );
  36. 36. 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
  37. 37. 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;
  38. 38. 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]);
  39. 39. 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); }} }}
  40. 40. 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"); }} }}
  41. 41. 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
  42. 42. 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
  43. 43. 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 {...}
  44. 44. 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…
  45. 45. 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
  46. 46. 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
  47. 47. 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
  48. 48. 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>
  49. 49. Language FeaturesLanguage Features DEMO 3: AttributesDEMO 3: Attributes  Create a Web service by using theCreate a Web service by using the [[WWebebMMethod] attributeethod] attribute
  50. 50. 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) { ...... }} }}
  51. 51. 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
  52. 52. 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:
  53. 53. 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); }}
  54. 54. 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);
  55. 55. 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…
  56. 56. 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;
  57. 57. 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)
  58. 58. 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
  59. 59. 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); }} }} }}
  60. 60. 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; ...... }}
  61. 61. 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); }}
  62. 62. 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
  63. 63. 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
  64. 64. 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#
  65. 65. Language FeaturesLanguage Features DEMO 6: Visual Studio .NETDEMO 6: Visual Studio .NET Windows programming with C#Windows programming with C#
  66. 66. 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)”
  67. 67. C# BooksC# Books
  68. 68. C# CustomersC# Customers
  69. 69. 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
  70. 70. Questions?Questions?
  71. 71. © 2001 Microsoft Corporation. All rights reserved.© 2001 Microsoft Corporation. All rights reserved.

×