Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | hollie-mitchell |
View: | 224 times |
Download: | 1 times |
Introduction to C#Introduction to C#
Enterprise ApplicationEnterprise Application Combines High productivity of RAD & Combines High productivity of RAD &
raw power of Craw power of C
1 - The .NET Framework1 - The .NET Framework
an integral Windows component an integral Windows component supports building and running the next supports building and running the next
generation of applications and XML generation of applications and XML Web services Web services
Designed to fulfill the following objectivesDesigned to fulfill the following objectives:: To provide a consistent objectTo provide a consistent object--oriented oriented
programming environment programming environment To provide a codeTo provide a code--execution execution
environmentenvironment minimizes software deployment and versioning minimizes software deployment and versioning
conflicts. conflicts. promotes safe execution of code promotes safe execution of code eliminates the performance problems of eliminates the performance problems of
scripted or interpreted environmentsscripted or interpreted environments..
To make the developer experience To make the developer experience consistent across widely varying types consistent across widely varying types of applications of applications
To build all communication on industry To build all communication on industry standards standards
has two main components :has two main components :
Common Language Runtime (CLR)Common Language Runtime (CLR) .NET Framework class library.NET Framework class library
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
The .NET FrameworkThe .NET FrameworkCommon Language RuntimeCommon Language Runtime
manages memory, thread execution, code execution, manages memory, thread execution, code execution, code safety verification, compilation, and other system code safety verification, compilation, and other system services services
enforces code access securityenforces code access security enforces code robustness by implementing a strict type-enforces code robustness by implementing a strict type-
and-code-verification infrastructure called the common and-code-verification infrastructure called the common type system (CTS).type system (CTS).
eliminates many common software issueseliminates many common software issues Example : automatically handles object layout & references that Example : automatically handles object layout & references that
resolves memory leaks and invalid memory references.resolves memory leaks and invalid memory references. accelerates developer productivity (Multiple languages)accelerates developer productivity (Multiple languages) designed for the software of the future, it also supports designed for the software of the future, it also supports
software of today and yesterdaysoftware of today and yesterday designed to enhance performancedesigned to enhance performance
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
Relationship to the Common Type System Relationship to the Common Type System and the Common Language Specificationand the Common Language Specification
CTS :CTS : The Common Type System is the model The Common Type System is the model
that defines the rules the common that defines the rules the common language runtime follows when declaring, language runtime follows when declaring, using, and managing types.using, and managing types.
The common type system establishes a The common type system establishes a framework that enables crossframework that enables cross--language language integration, type safety, and highintegration, type safety, and high--performance code execution.performance code execution.
CLS :CLS : CLS is a sort of lingua franca that ensures CLS is a sort of lingua franca that ensures
seamless interoperability between CLS-compliant seamless interoperability between CLS-compliant languages and class libraries languages and class libraries
The Common Language Specification The Common Language Specification ((CLSCLS) ) defines a set of programmatically verifiable rules defines a set of programmatically verifiable rules that governs the interoperation of types authored that governs the interoperation of types authored in different programming languages in different programming languages
Targeting the CLS is an excellent way to ensure Targeting the CLS is an excellent way to ensure crosscross--language interoperation language interoperation
Managed class library designers can use the CLS Managed class library designers can use the CLS to guarantee that their APIs are callable from a to guarantee that their APIs are callable from a wide range of programming languages wide range of programming languages
Relationship to the Common Type System Relationship to the Common Type System and the Common Language Specificationand the Common Language Specification
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
AgendaAgenda
Hello WorldHello World The .NET FrameworkThe .NET Framework Design Goals of C#Design Goals of C# Language FeaturesLanguage Features
Design Goals of C#Design Goals of C#The Big IdeasThe Big Ideas
The first component oriented The first component oriented language in the C/C++ familylanguage in the C/C++ family
Everything really is an objectEverything really is an object Next generation robust and Next generation robust and
durable softwaredurable software Preserving your investmentPreserving your investment
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 header files, IDL, etc.No header files, IDL, etc. Can be embedded in ASP pagesCan be embedded in ASP pages
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
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
Design Goals of C#Design Goals of C# Preserving Your InvestmentPreserving Your Investment
C++ HeritageC++ Heritage Namespaces, pointers (in unsafe code), Namespaces, pointers (in unsafe code),
unsigned types, etc.unsigned types, etc. No unnecessary sacrificesNo unnecessary sacrifices
InteroperabilityInteroperability What software is increasingly aboutWhat software is increasingly about C# talks to XML, SOAP, COM, DLLs, and C# talks to XML, SOAP, COM, DLLs, and
any .NET Framework languageany .NET Framework language
Millions of lines of C# code in .NETMillions of lines of C# code in .NET Short learning curveShort learning curve Increased productivityIncreased productivity
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
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 if (top == null) throw new InvalidOperationException();InvalidOperationException(); object result = top.data;object result = top.data; top = top.next;top = top.next; return result;return result; }} }}}}
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"
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();
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
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
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
Language FeaturesLanguage Features Classes and StructsClasses and Structs
class CPoint { int x, y; ... }class CPoint { int x, y; ... }struct SPoint { int x, y; ... }struct SPoint { int x, y; ... }
CPoint cp = new CPoint(10, 20);CPoint cp = new CPoint(10, 20);SPoint sp = new SPoint(10, 20);SPoint sp = new SPoint(10, 20);
1010
2020spsp
cpcp
1010
2020
CPointCPoint
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) {...}}}
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,}}
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);
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
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
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);
Hashtable t = new Hashtable();Hashtable t = new Hashtable();t.Add(0, "zero");t.Add(0, "zero");t.Add(1, "one");t.Add(1, "one");t.Add(2, "two");t.Add(2, "two");
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
Components are easy to build and Components are easy to build and to consumeto consume
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;
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 index] public string this[int 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]);
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); } }}}
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 += new okButton.Click += new EventHandler(OkButtonClick);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"); }}}}
Language FeaturesLanguage FeaturesDEMO 2: Creating an Event HandlerDEMO 2: Creating an Event Handler
Define an Event Handler for a button in Define an Event Handler for a button in a Windows Forms applicationa Windows Forms application
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
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 {...}
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…
Language FeaturesLanguage FeaturesDEMO 3: AttributesDEMO 3: Attributes
Create a Web service by using the Create a Web service by using the [webmethod] attribute[webmethod] attribute
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) { ...... }}}}
Language FeaturesLanguage FeaturesDEMO 4: XML CommentsDEMO 4: XML Comments
Show how the compiler can auto Show how the compiler can auto generate documentation from the generate documentation from the source code using XML commentssource code using XML comments
Language FeaturesLanguage FeaturesStatements and ExpressionsStatements and Expressions
High C++ fidelityHigh C++ fidelity If, while, do require bool conditionIf, while, do require bool condition Goto can’t jump into blocksGoto can’t jump into blocks Switch statementSwitch statement
No fall-through, “goto case” or “goto default”No fall-through, “goto case” or “goto default” Foreach statementForeach statement Checked and Checked and
uncheckeduncheckedstatementsstatements
Expression Expression statements statements must do workmust do work
void Foo() {void Foo() { i == 1; // errori == 1; // error}}
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);}}
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);
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…
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;
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)
class Derived: Baseclass Derived: Base // // version 1version 1{{ public virtual void Foo() {public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}
class Derived: Baseclass Derived: Base // // version 2aversion 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
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); }} }}}}
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; ......}}
Language FeaturesLanguage Features Unsafe CodeUnsafe Code
class FileStream: Streamclass FileStream: Stream{{ int handle;int handle;
public unsafe int Read(byte[] buffer, int index, int public unsafe int Read(byte[] buffer, int index, int count) {count) { int n = 0;int n = 0; fixed (byte* p = buffer) {fixed (byte* p = buffer) { ReadFile(handle, p + index, count, &n, null);ReadFile(handle, p + index, count, &n, null); }} return n;return n; }}
[dllimport("kernel32", SetLastError=true)][dllimport("kernel32", SetLastError=true)] static extern unsafe bool ReadFile(int hFile,static extern unsafe bool ReadFile(int hFile, void* lpBuffer, int nBytesToRead,void* lpBuffer, int nBytesToRead, int* nBytesRead, Overlapped* lpOverlapped);int* nBytesRead, Overlapped* lpOverlapped);}}
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
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