Advanced C# - unibo.itlia.deis.unibo.it/Courses/IngSwA0910/Slide_NET3x2.pdf · 1 Advanced C#...
Transcript of Advanced C# - unibo.itlia.deis.unibo.it/Courses/IngSwA0910/Slide_NET3x2.pdf · 1 Advanced C#...
1
Advanced C
Mark Sapossnek
CS 594Computer Science Department
Metropolitan CollegeBoston University
Prerequisites
This module assumes that you understand the fundamentals of
ProgrammingVariables statements functions loops etc
Object-oriented programming Classes inheritance polymorphism members etcC++ or Java
Introduction to C
2
Learning Objectives
Advanced features of the C languageCreating custom types with interfaces classes and structsDelegates and eventsMiscellaneous topics
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
3
Objects instances and classes
IdentityEvery instance has a unique identity regardless of its data
EncapsulationData and function are packaged togetherInformation hidingAn object is an abstraction
User should NOT know implementation details
Review Key Object-Oriented Concepts
Review Key Object-Oriented Concepts
InterfacesA well-defined contractA set of function members
TypesAn object has a type which specifies its interfaces and their implementationsA variable also can have a type
InheritanceTypes are arranged in a hierarchy
Basederived superclasssubclass
Interface vs implementation inheritance
4
Review Key Object-Oriented Concepts
PolymorphismThe ability to use an object without knowing its precise typeThree main kinds of polymorphism
InheritanceInterfacesLate binding
DependenciesFor reuse and to facilitate development systems should be loosely coupledDependencies should be minimized
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
5
Interfaces
An interface defines a contractAn interface is a typeIncludes methods properties indexers eventsAny class or struct implementing an interface must support all parts of the contract
Interfaces provide no implementationWhen a class or struct implements an interface it must provide the implementation
Interfaces provide polymorphismMany classes and structs may implement a particular interface
public interface IDelete void Delete()
public class TextBox IDelete
public void Delete() public class Car IDelete
public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
InterfacesExample
6
interface IControl void Paint()
interface IListBox IControl void SetItems(string[] items)
interface IComboBox ITextBox IListBox
InterfacesMultiple Inheritance
Classes and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces
interface IControl void Delete()
interface IListBox IControl void Delete()
interface IComboBox ITextBox IListBox
void IControlDelete()
void IListBoxDelete()
InterfacesExplicit Interface Members
If two interfaces have the same method name you can explicitly specify interface + method name to disambiguate their implementations
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
2
Learning Objectives
Advanced features of the C languageCreating custom types with interfaces classes and structsDelegates and eventsMiscellaneous topics
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
3
Objects instances and classes
IdentityEvery instance has a unique identity regardless of its data
EncapsulationData and function are packaged togetherInformation hidingAn object is an abstraction
User should NOT know implementation details
Review Key Object-Oriented Concepts
Review Key Object-Oriented Concepts
InterfacesA well-defined contractA set of function members
TypesAn object has a type which specifies its interfaces and their implementationsA variable also can have a type
InheritanceTypes are arranged in a hierarchy
Basederived superclasssubclass
Interface vs implementation inheritance
4
Review Key Object-Oriented Concepts
PolymorphismThe ability to use an object without knowing its precise typeThree main kinds of polymorphism
InheritanceInterfacesLate binding
DependenciesFor reuse and to facilitate development systems should be loosely coupledDependencies should be minimized
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
5
Interfaces
An interface defines a contractAn interface is a typeIncludes methods properties indexers eventsAny class or struct implementing an interface must support all parts of the contract
Interfaces provide no implementationWhen a class or struct implements an interface it must provide the implementation
Interfaces provide polymorphismMany classes and structs may implement a particular interface
public interface IDelete void Delete()
public class TextBox IDelete
public void Delete() public class Car IDelete
public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
InterfacesExample
6
interface IControl void Paint()
interface IListBox IControl void SetItems(string[] items)
interface IComboBox ITextBox IListBox
InterfacesMultiple Inheritance
Classes and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces
interface IControl void Delete()
interface IListBox IControl void Delete()
interface IComboBox ITextBox IListBox
void IControlDelete()
void IListBoxDelete()
InterfacesExplicit Interface Members
If two interfaces have the same method name you can explicitly specify interface + method name to disambiguate their implementations
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
3
Objects instances and classes
IdentityEvery instance has a unique identity regardless of its data
EncapsulationData and function are packaged togetherInformation hidingAn object is an abstraction
User should NOT know implementation details
Review Key Object-Oriented Concepts
Review Key Object-Oriented Concepts
InterfacesA well-defined contractA set of function members
TypesAn object has a type which specifies its interfaces and their implementationsA variable also can have a type
InheritanceTypes are arranged in a hierarchy
Basederived superclasssubclass
Interface vs implementation inheritance
4
Review Key Object-Oriented Concepts
PolymorphismThe ability to use an object without knowing its precise typeThree main kinds of polymorphism
InheritanceInterfacesLate binding
DependenciesFor reuse and to facilitate development systems should be loosely coupledDependencies should be minimized
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
5
Interfaces
An interface defines a contractAn interface is a typeIncludes methods properties indexers eventsAny class or struct implementing an interface must support all parts of the contract
Interfaces provide no implementationWhen a class or struct implements an interface it must provide the implementation
Interfaces provide polymorphismMany classes and structs may implement a particular interface
public interface IDelete void Delete()
public class TextBox IDelete
public void Delete() public class Car IDelete
public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
InterfacesExample
6
interface IControl void Paint()
interface IListBox IControl void SetItems(string[] items)
interface IComboBox ITextBox IListBox
InterfacesMultiple Inheritance
Classes and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces
interface IControl void Delete()
interface IListBox IControl void Delete()
interface IComboBox ITextBox IListBox
void IControlDelete()
void IListBoxDelete()
InterfacesExplicit Interface Members
If two interfaces have the same method name you can explicitly specify interface + method name to disambiguate their implementations
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
4
Review Key Object-Oriented Concepts
PolymorphismThe ability to use an object without knowing its precise typeThree main kinds of polymorphism
InheritanceInterfacesLate binding
DependenciesFor reuse and to facilitate development systems should be loosely coupledDependencies should be minimized
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
5
Interfaces
An interface defines a contractAn interface is a typeIncludes methods properties indexers eventsAny class or struct implementing an interface must support all parts of the contract
Interfaces provide no implementationWhen a class or struct implements an interface it must provide the implementation
Interfaces provide polymorphismMany classes and structs may implement a particular interface
public interface IDelete void Delete()
public class TextBox IDelete
public void Delete() public class Car IDelete
public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
InterfacesExample
6
interface IControl void Paint()
interface IListBox IControl void SetItems(string[] items)
interface IComboBox ITextBox IListBox
InterfacesMultiple Inheritance
Classes and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces
interface IControl void Delete()
interface IListBox IControl void Delete()
interface IComboBox ITextBox IListBox
void IControlDelete()
void IListBoxDelete()
InterfacesExplicit Interface Members
If two interfaces have the same method name you can explicitly specify interface + method name to disambiguate their implementations
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
5
Interfaces
An interface defines a contractAn interface is a typeIncludes methods properties indexers eventsAny class or struct implementing an interface must support all parts of the contract
Interfaces provide no implementationWhen a class or struct implements an interface it must provide the implementation
Interfaces provide polymorphismMany classes and structs may implement a particular interface
public interface IDelete void Delete()
public class TextBox IDelete
public void Delete() public class Car IDelete
public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
InterfacesExample
6
interface IControl void Paint()
interface IListBox IControl void SetItems(string[] items)
interface IComboBox ITextBox IListBox
InterfacesMultiple Inheritance
Classes and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces
interface IControl void Delete()
interface IListBox IControl void Delete()
interface IComboBox ITextBox IListBox
void IControlDelete()
void IListBoxDelete()
InterfacesExplicit Interface Members
If two interfaces have the same method name you can explicitly specify interface + method name to disambiguate their implementations
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
6
interface IControl void Paint()
interface IListBox IControl void SetItems(string[] items)
interface IComboBox ITextBox IListBox
InterfacesMultiple Inheritance
Classes and structs can inherit from multiple interfacesInterfaces can inherit from multiple interfaces
interface IControl void Delete()
interface IListBox IControl void Delete()
interface IComboBox ITextBox IListBox
void IControlDelete()
void IListBoxDelete()
InterfacesExplicit Interface Members
If two interfaces have the same method name you can explicitly specify interface + method name to disambiguate their implementations
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
7
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Classes and StructsSimilarities
Both are user-defined types
Both can implement multiple interfacesBoth can contain
Data Fields constants events arrays
Functions Methods properties indexers operators constructors
Type definitionsClasses structs enums interfaces delegates
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
8
No user-defined parameterlessconstructor
Can have user-definedparameterless constructor
No destructorCan have a destructor
No inheritance(inherits only from SystemValueType)
Can inherit from any non-sealed reference type
Value typeReference type
StructClass
Classes and StructsDifferences
Members can be public internal or private
Members are always public
Always allocated on the stack or as a member
Can be allocated on the heap on the stack or as a member (can be used as value or reference)
User-defined value typeSame as C++ class but all members are public
C StructC++ Struct
Classes and StructsC Structs vs C++ Structs
Very different from C++ struct
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
9
public class Car Vehicle
public enum Make GM Honda BMW
Make make
string vid
Point location
Car(Make m string vid Point loc)
thismake = m
thisvid = vid
thislocation = loc
public void Drive() ConsoleWriteLine(ldquovroomrdquo)
Car c =new Car(CarMakeBMW
ldquoJF3559QT98rdquo new Point(37))
cDrive()
Classes and StructsClass
public struct Point int x ypublic Point(int x int y) thisx = x thisy = y
public int X get return x
set x = value public int Y get return y
set y = value
Point p = new Point(25)pX += 100int px = pX px = 102
Classes and StructsStruct
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
10
Classes and StructsStatic vs Instance Members
By default members are per instanceEach instance gets its own fieldsMethods apply to a specific instance
Static members are per typeStatic methods canrsquot access instance dataNo this variable in static methods
Donrsquot abuse static membersThey are essentially object-oriented global data and global functions
Classes and StructsAccess Modifiers
Access modifiers specify who can use a type or a memberAccess modifiers control encapsulationTop-level types (those directly in a namespace) can be public or internal Class members can be public private protected internal orprotected internal
Struct members can be public private or internal
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
11
to T or types derived from Tprotected
within T only (the default)private
to T or types derived from Tor to types within A
protected internal
to types within Ainternal
to everyonepublic
Then a member defined in type T and assembly A is accessible
If the access modifier is
Classes and StructsAccess Modifiers
Classes and StructsAbstract Classes
An abstract class is one that cannot be instantiatedIntended to be used as a base class
May contain abstract and non-abstract function membersSimilar to an interface
Cannot be sealed
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
12
Classes and StructsSealed Classes
A sealed class is one that cannot be used as a base classSealed classes canrsquot be abstract
All structs are implicitly sealedWhy seal a class
To prevent unintended derivationCode optimization
Virtual function calls can be resolved at compile-time
class Person string namepublic Person(string name) thisname = name
public void Introduce(Person p) if (p = this)ConsoleWriteLine(ldquoHi Irsquom ldquo + name)
Classes and Structsthis
The this keyword is a predefined variable available in non-static function members
Used to access data and function members unambiguously
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
13
class Shape int x ypublic override string ToString() return x= + x + y= + y
class Circle Shape
int rpublic override string ToString() return baseToString() + r= + r
Classes and Structsbase
The base keyword is used to access class members that are hidden by similarly named members of the current class
public class MyClass public const string version = ldquo100rdquopublic const string s1 = ldquoabcrdquo + ldquodefrdquopublic const int i3 = 1 + 2public const double PI_I3 = i3 MathPIpublic const double s = MathSin(MathPI) ERROR
Classes and StructsConstants
A constant is a data member that is evaluated at compile-time and is implicitly static (per type)
eg MathPI
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
14
Classes and StructsFields
A field is a member variable
Holds data for a class or structCan hold
a class instance (a reference) a struct instance (actual data) or an array of class or struct instances (an array is actually a reference)
Classes and StructsReadonly Fields
Similar to a const but is initialized at run-time in its declaration or in a constructor
Once initialized it cannot be modified
Differs from a constant Initialized at run-time (vs compile-time)
Donrsquot have to re-compile clients
Can be static or per-instance
public class MyClass public static readonly double d1 = MathSin(MathPI)public readonly string s1public MyClass(string s) s1 = s
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
15
public class Button Control private string captionpublic string Caption
get return caption set caption = value
Repaint()
Button b = new Button()bCaption = OKString s = bCaption
Classes and StructsProperties
A property is a virtual field
Looks like a field but is implemented with code
Can be read-only write-only or readwrite
public class ListBox Control private string[] itemspublic string this[int index]
get return items[index] set items[index] = value
Repaint()
ListBox listBox = new ListBox()listBox[0] = helloConsoleWriteLine(listBox[0])
Classes and StructsIndexers
An indexer lets an instance behave as a virtual arrayCan be overloaded (eg index by int and by string)
Can be read-only write-only or readwrite
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
16
Classes and StructsMethods
All code executes in a methodConstructors destructors and operators are special types of methodsProperties and indexers are implemented with getset methods
Methods have argument lists
Methods contain statementsMethods can return a value
Only if return type is not void
Classes and StructsMethod Argument Passing
By default data is passed by value
A copy of the data is created and passed to the method
For value types variables cannot be modified by a method callFor reference types the instance can be modified by a method call but the variable itself cannot be modified by a method call
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
17
void RefFunction(ref int p) p++
int x = 10RefFunction(ref x) x is now 11
Classes and StructsMethod Argument Passing
The ref modifier causes arguments to be passed by referenceAllows a method call to modify a variable
Have to use ref modifier in method definition and the code that calls itVariable has to have a value before call
void OutFunction(out int p) p = 22
int xOutFunction(out x) x is now 22
Classes and StructsMethod Argument Passing
The out modifier causes arguments to be passed out by referenceAllows a method call to initialize a variable
Have to use out modifier in method definition and the code that calls itArgument has to have a value before returning
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
18
void Print(int i)void Print(string s)void Print(char c)void Print(float f)int Print(float f) Error duplicate signature
Classes and StructsOverloaded Methods
A type may overload methods ie provide multiple methods with the same nameEach must have a unique signature
Signature is based upon arguments only the return value is ignored
int Sum(params int[] intArr) int sum = 0foreach (int i in intArr)sum += i
return sum
int sum = Sum(138734)
Classes and StructsParameter Arrays
Methods can have a variable number of arguments called a parameter arrayparams keyword declares parameter array
Must be last argument
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
19
class Foo public void DoSomething(int i)
Foo f = new Foo()
fDoSomething()
Classes and StructsVirtual Methods
Methods may be virtual or non-virtual (default)
Non-virtual methods are not polymorphicThey cannot be overridden
Non-virtual methods cannot be abstract
Classes and StructsVirtual Methods
Defined in a base class
Can be overridden in derived classesDerived classes provide their own specialized implementation
May contain a default implementationUse abstract method if no default implementation
A form of polymorphism
Properties indexers and events can also be virtual
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
20
class Shape public virtual void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape())
Classes and StructsVirtual Methods
Classes and StructsAbstract Methods
An abstract method is virtual and has no implementationMust belong to an abstract class
Intended to be implemented in a derived class
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
21
abstract class Shape public abstract void Draw()
class Box Shape
public override void Draw() class Sphere Shape
public override void Draw()
void HandleShape(Shape s) sDraw()
HandleShape(new Box())HandleShape(new Sphere())HandleShape(new Shape()) Error
Classes and StructsAbstract Methods
Classes and StructsMethod Versioning
Must explicitly use override or new keywords to specify versioning intentAvoids accidental overriding
Methods are non-virtual by defaultC++ and Java product fragile base classes ndashcannot specify versioning intent
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
22
class Derived Base version 1public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Base version 1
Classes and StructsMethod Versioning
class Base version 2 public virtual void Foo()
ConsoleWriteLine(BaseFoo)
class Derived Base version 2anew public virtual void Foo()
ConsoleWriteLine(DerivedFoo)
class Derived Base version 2bpublic override void Foo()
baseFoo()ConsoleWriteLine(DerivedFoo)
Classes and StructsConstructors
Instance constructors are special methods that are called when a class or struct is instantiatedPerforms custom initialization
Can be overloadedIf a class doesnrsquot define any constructors an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct
All fields initialized to zeronull
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
23
class B private int hpublic B() public B(int h) thish = h
class D B
private int ipublic D() this(24) public D(int i) thisi = i public D(int h int i) base(h) thisi = i
Classes and StructsConstructor Initializers
One constructor can call another with a constructor initializerCan call this() or base()Default constructor initializer is base()
Classes and StructsStatic Constructors
A static constructor lets you create initialization code that is called once for the classGuaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessedNo other guarantees on execution order
Only one static constructor per typeMust be parameterless
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
24
class Foo ~Foo()
ConsoleWriteLine(ldquoDestroyed 0rdquo this)
Classes and StructsDestructors
A destructor is a method that is called before an instance is garbage collectedUsed to clean up any resources held by the instance do bookkeeping etc
Only classes not structs can have destructors
Classes and StructsDestructors
Unlike C++ C destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdownUse the using statement and theIDisposable interface to achieve deterministic finalization
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
25
class Car string vidpublic static bool operator ==(Car x Car y) return xvid == yvid
Classes and StructsOperator Overloading
User-defined operators
Must be a static method
Classes and StructsOperator Overloading
--++falsetrue
~-+
Overloadable unary operators
Overloadable binary operators
gt=
=
~
lt=gtltgtgtltlt
==^|amp
-+
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
26
Classes and StructsOperator Overloading
No overloading for member access method invocation assignment operators nor these operators sizeof new is as typeof checked unchecked ampamp || and
The ampamp and || operators are automatically evaluated from amp and |Overloading a binary operator (eg ) implicitly overloads the corresponding assignment operator (eg =)
Classes and StructsOperator Overloading
struct Vector int x ypublic Vector(x y) thisx = x thisy = y public static Vector operator +(Vector a Vector b) return Vector(ax + bx ay + by)
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
27
class Note int value Convert to hertz ndash no loss of precisionpublic static implicit operator double(Note x) return
Convert to nearest notepublic static explicit operator Note(double x) return
Note n = (Note)442578double d = n
Classes and StructsConversion Operators
User-defined explicit and implicit conversions
Classes and StructsImplementing Interfaces
Classes and structs can implement multiple interfacesA class or struct that inherits from an interface must implement all function members defined in that interface
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
28
public interface IDelete void Delete()
public class TextBox IDelete public void Delete()
public class Car IDelete public void Delete()
TextBox tb = new TextBox()IDelete iDel = tbiDelDelete()
Car c = new Car()iDel = ciDelDelete()
Classes and StructsImplementing Interfaces
public interface IDelete void Delete()
public interface IFoo void Delete()
public class TextBox IDelete IFoo public void IDeleteDelete() public void IFooDelete()
Classes and StructsImplementing Interfaces
Explicit interface implementation
Handles name collisions
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
29
Classes and StructsNested Types
Declared within the scope of another typeNesting a type provides three benefits
Nested type can access all the members of its enclosing type regardless of access modiferNested type can be hidden from other typesAccessing a nested type from outside the enclosing type requires specifying the type name
Nested types can be declared new to hide inherited typesUnlike Java inner classes nested types imply no relationship between instances
Classes and Structsis Operator
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
static void DoSomething(object o) if (o is Car) ((Car)o)Drive()
Donrsquot abuse the is operator it is preferable to design an appropriate type hierarchy with polymorphic methods
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
30
Classes and Structsas Operator
The as operator tries to convert a variable to a specified type if no such conversion is possible the result is null
static void DoSomething(object o) Car c = o as Carif (c = null) cDrive()
More efficient than using is operator test and convert in one operationSame design warning as with the is operator
Classes and Structstypeof Operator
The typeof operator returns the SystemTypeobject for a specified typeCan then use reflection to dynamically obtain information about the type
ConsoleWriteLine(typeof(int)FullName)ConsoleWriteLine(typeof(SystemInt)Name)ConsoleWriteLine(typeof(float)Module)ConsoleWriteLine(typeof(double)IsPublic)ConsoleWriteLine(typeof(Car)MemberType)
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
31
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
DelegatesOverview
A delegate is a reference type that defines a method signature
A delegate instance holds one or more methodsEssentially an ldquoobject-oriented function pointerrdquo
Methods can be static or non-static
Methods can return a value
Provides polymorphism for individual functions
Foundation for event handling
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
32
DelegatesOverview
delegate double Del(double x) Declare
static void DemoDelegates() Del delInst = new Del(MathSin) Instantiatedouble x = delInst(10) Invoke
DelegatesMulticast Delegates
A delegate can hold and invoke multiple methods
Multicast delegates must contain only methods that return void else there is a run-time exception
Each delegate has an invocation listMethods are invoked sequentially in the order added
The += and -= operators are used to add and remove delegates respectively
+= and -= operators are thread-safe
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
33
DelegatesMulticast Delegates
delegate void SomeEvent(int x int y)static void Foo1(int x int y) ConsoleWriteLine(Foo1)
static void Foo2(int x int y) ConsoleWriteLine(Foo2)
public static void Main() SomeEvent func = new SomeEvent(Foo1)func += new SomeEvent(Foo2)func(12) Foo1 and Foo2 are calledfunc -= new SomeEvent(Foo1)func(23) Only Foo2 is called
Delegatesand Interfaces
Could always use interfaces instead of delegates
Interfaces are more powerfulMultiple methodsInheritance
Delegates are more elegant for event handlersLess codeCan easily implement multiple event handlers on one classstruct
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
34
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
EventsOverview
Event handling is a style of programming where one object notifies another that something of interest has occurred
A publish-subscribe programming model
Events allow you to tie your own code into the functioning of an independently created component
Events are a type of ldquocallbackrdquo mechanism
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
35
EventsOverview
Events are well suited for user-interfacesThe user does something (clicks a button moves a mouse changes a value etc) and the program reacts in response
Many other uses egTime-based eventsAsynchronous operation completedEmail message has arrivedA web session has begun
EventsOverview
C has native support for events
Based upon delegatesAn event is essentially a field holding a delegate
However public users of the class can only register delegates
They can only call += and -=They canrsquot invoke the eventrsquos delegate
Multicast delegates allow multiple objects to register with the same event
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
36
EventsExample Component-Side
Define the event signature as a delegate
Define the event and firing logic
public delegate void EventHandler(object senderEventArgs e)
public class Button public event EventHandler Click
protected void OnClick(EventArgs e) This is called when button is clickedif (Click = null) Click(this e)
EventsExample User-Side
Define and register an event handler
public class MyForm Form Button okButton
static void OkClicked(object sender EventArgs e) ShowMessage(You pressed the OK button)
public MyForm() okButton = new Button()okButtonCaption = OKokButtonClick += new EventHandler(OkClicked)
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
37
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
AttributesOverview
Itrsquos often necessary to associate information (metadata) with types and members eg
Documentation URL for a classTransaction context for a methodXML persistence mappingCOM ProgID for a class
Attributes allow you to decorate a code element (assembly module type member return value and parameter) with additional information
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
38
AttributesOverview
[HelpUrl(ldquohttpSomeUrlAPIDocsSomeClassrdquo)]class SomeClass [Obsolete(ldquoUse SomeNewMethod insteadrdquo)]public void SomeOldMethod()
public string Test([SomeAttr()] string param1)
AttributesOverview
Attributes are superior to the alternativesModifying the source languageUsing external files eg IDL DEF
Attributes are extensibleAttributes allow to you add information not supported by C itselfNot limited to predefined information
Built into the NET Framework so they work across all NET languages
Stored in assembly metadata
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
39
AttributesOverview
COM Prog IDProgId
Transactional characteristics of a classTransaction
Compiler will complain if target is usedObsolete
Allows a class or struct to be serializedSerializable
Should a property or event be displayed in the property window
Browsable
DescriptionAttribute Name
Some predefined NET Framework attributes
AttributesOverview
Attributes can beAttached to types and membersExamined at run-time using reflection
Completely extensibleSimply a class that inherits from SystemAttribute
Type-safeArguments checked at compile-time
Extensive use in NET FrameworkXML Web Services security serialization component model COM and PInvoke interop code configurationhellip
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
40
AttributesQuerying Attributes
[HelpUrl(httpSomeUrlMyClass)] class Class1 [HelpUrl(httpSomeUrlMyClass)HelpUrl(httpSomeUrlMyClassrdquo Tag=ldquoctorrdquo)] class Class2
Type type = typeof(MyClass)foreach (object attr in typeGetCustomAttributes() ) if ( attr is HelpUrlAttribute ) HelpUrlAttribute ha = (HelpUrlAttribute) attrmyBrowserNavigate( haUrl )
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
41
C provides preprocessor directives that serve a number of functionsUnlike C++ there is not a separate preprocessor
The ldquopreprocessorrdquo name is preserved only for consistency with C++
C++ preprocessor features removed includeinclude Not really needed with one-stop programming removal results in faster compilationMacro version of define removed for clarity
Preprocessor DirectivesOverview
Preprocessor DirectivesOverview
Delimit outline regionsregion end
Specify line numberline
Issue errors and warningserror warning
Conditionally skip sections of codeif elif else endif
Define and undefine conditional symbolsdefine undef
DescriptionDirective
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
42
define Debugpublic class Debug [Conditional(Debug)]public static void Assert(bool cond String s) if (cond) throw new AssertionException(s)
void DoSomething() If Debug is not defined the next line is not even calledAssert((x == y) ldquoX should equal Yrdquo)
Preprocessor DirectivesConditional Compilation
Preprocessor DirectivesAssertions
By the way assertions are an incredible way to improve the quality of your codeAn assertion is essentially a unit test built right into your codeYou should have assertions to test preconditions postconditions and invariantsAssertions are only enabled in debug buildsYour code is QArsquod every time it runsMust read ldquoWriting Solid Coderdquo by Steve Maguire Microsoft Press ISBN 1-55615-551-4
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
43
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
XML CommentsOverview
Programmers donrsquot like to document code so we need a way to make it easy for them to produce quality up-to-date documentationC lets you embed XML comments that document types members parameters etc
Denoted with triple slash
XML document is generated when code is compiled with doc argumentComes with predefined XML schema but you can add your own tags too
Some are verified eg parameters exceptions types
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
44
XML CommentsOverview
Formatting hintsltlistgt ltitemgt
Use of a parameterltparamrefgt
Cross referencesltseegt ltseealsogt
Sample codeltexamplegt ltcgt ltcodegt
Propertyltvaluegt
Exceptions thrown from methodltexceptiongt
Permission requirementsltpermissiongt
Method return valueltreturnsgt
Method parameterltparamgt
Type or memberltsummarygt ltremarksgt
DescriptionXML Tag
class XmlElement ltsummarygt Returns the attribute with the given name and namespaceltsummarygt ltparam name=namegt The name of the attributeltparamgt ltparam name=nsgt The namespace of the attribute or null if the attribute has no namespaceltparamgt ltreturngt The attribute value or null if the attribute does not existltreturngt ltseealso cref=GetAttr(string)gtpublic string GetAttr(string name string ns)
XML CommentsOverview
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
45
Agenda
Review Object-Oriented ConceptsInterfacesClasses and StructsDelegatesEventsAttributesPreprocessor DirectivesXML CommentsUnsafe Code
Unsafe CodeOverview
Developers sometime need total controlPerformance extremesDealing with existing binary structuresExisting codeAdvanced COM support DLL import
C allows you to mark code as unsafe allowingPointer types pointer arithmetic -gt operatorsUnsafe castsNo garbage collection
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
46
unsafe void Foo() char buf = stackalloc char[256]for (char p = buf p lt buf + 256 p++) p = 0
Unsafe CodeOverview
Lets you embed native CC++ codeBasically ldquoinline CrdquoMust ensure the GC doesnrsquot move your data
Use fixed statement to pin dataUse stackalloc operator so memory is allocated on stack and need not be pinned
class FileStream Stream int handle
public unsafe int Read(byte[] buffer int indexint count)
int n = 0fixed (byte p = buffer) ReadFile(handle p + index count ampn null)
return n
[dllimport(kernel32 SetLastError=true)]static extern unsafe bool ReadFile(int hFilevoid lpBuffer int nBytesToReadint nBytesRead Overlapped lpOverlapped)
Unsafe CodeOverview
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm
47
Unsafe CodeC and Pointers
Power comes at a priceUnsafe means unverifiable codeStricter security requirements
Before the code can runDownloading code
More Resources
httpmsdnmicrosoftcom
httpwindowsoreillycomnewshejlsberg_0800html
httpwwwcsharphelpcom
httpwwwcsharp-stationcom
httpwwwcsharpindexcom
httpmsdnmicrosoftcommsdnmagissues0900csharpcsharpasp
httpwwwhitmillcomprogrammingdotNETcsharphtml
httpwwwc-sharpcornercom
httpmsdnmicrosoftcomlibrarydefaultaspURL=librarydotnetcsspecvclrfcsharpspec_Starthtm