Advanced C#.ppt
Transcript of Advanced C#.ppt
-
7/23/2019 Advanced C#.ppt
1/85
Advanced C#
Extracted from (with very minor modifications)
Mark Sapossnek
CS 594
Compter Science !epartment
Metropo"itan Co""ee$oston %niversity
&ind the oriina" set on '''ot!ot*etcom
+im &awcettCSE ,-. / Software Mode"in 0 Ana"ysis
-
7/23/2019 Advanced C#.ppt
2/85
1earnin 23ectives
Advanced features of the C# language Creating custom types with interfaces, classes
and structs
Delegates and events
Miscellaneous topics
-
7/23/2019 Advanced C#.ppt
3/85
Aenda
eview 23ect62riented Concepts
Interfaces
Classes and Structs
Delegates
Events
Attributes
reprocessor Directives
!M" Comments
nsafe Code
-
7/23/2019 Advanced C#.ppt
4/85
$b%ects, instances and classes
Identity
Every instance has a uni&ue identity, regardless ofits data
Encapsulation Data and function are pac'aged together
Information hiding
An ob%ect is an abstraction ser should ($) 'now implementation details
eview7ey 23ect62riented Concepts
-
7/23/2019 Advanced C#.ppt
5/85
eview7ey 23ect62riented Concepts
Interfaces A well*defined contract A set of function members
)ypes An ob%ect has a type, which specifies its interfaces and
their implementations A variable also can have a type
Inheritance )ypes are arranged in a hierarchy
+asederived, superclasssubclass
Interface vs- implementation inheritance
-
7/23/2019 Advanced C#.ppt
6/85
eview7ey 23ect62riented Concepts
olymorphism )he ability to use an ob%ect without 'nowing its
precise type )hree main 'inds of polymorphism
Inheritance Interfaces "ate binding
Dependencies .or reuse and to facilitate development, systems
should be loosely coupled Dependencies should be minimi/ed
-
7/23/2019 Advanced C#.ppt
7/85
8nterfaces
An interface defines a contract An interface is a type Includes methods, properties, inde0ers, events Any class or struct implementing an interface must
support all parts of the contract
Interfaces provide no implementation 1hen a class or struct implements an interface it
must provide the implementation
Interfaces provide polymorphism Many classes and structs may implement
a particular interface
-
7/23/2019 Advanced C#.ppt
8/85
public interface IDelete { void Delete();}public class TextBox : IDelete {
public void Delete() { ... }}public class Car : IDelete { public void Delete() { ... }}
TextBox tb = ne TextBox();
IDelete iDel = tb;iDel.Delete();
Car c = ne Car();iDel = c;iDel.Delete();
8nterfacesExamp"e
-
7/23/2019 Advanced C#.ppt
9/85
interface IControl { void !aint();}
interface I"istBox: IControl { void #etIte$s(strin%&' ite$s);}
interface ICo$boBox: ITextBox I"istBox {
}
8nterfacesM"tip"e 8nheritance
Classes and structs can inherit from
multiple interfaces
Interfaces can inherit from multiple interfaces
-
7/23/2019 Advanced C#.ppt
10/85
interface IControl { void Delete();}
interface I"istBox: IControl { void Delete();
}interface ICo$boBox: ITextBox I"istBox {
void IControl.Delete();
void I"istBox.Delete();
}
8nterfacesExp"icit 8nterface Mem3ers
If two interfaces have the same method name,
you can e0plicitly specify interface 2 method
name to disambiguate their implementations
-
7/23/2019 Advanced C#.ppt
11/85
C"asses and StrctsSimi"arities
+oth are user*defined types
+oth can implement multiple interfaces
+oth can contain Data
.ields, constants, events, arrays
.unctions Methods, properties, inde0ers, operators, constructors
)ype definitions Classes, structs, enums, interfaces, delegates
-
7/23/2019 Advanced C#.ppt
12/85
C"ass Strct
3eference type 4alue type
Can inherit from anynon*sealed reference type
(o inheritance5inherits only fromSystem.ValueType6
Can have a destructor (o destructor
Can have user*definedparameterless constructor
(o user*defined parameterlessconstructor
C"asses and Strcts!ifferences
-
7/23/2019 Advanced C#.ppt
13/85
C Strct C# Strct
Same as C22 class, but allmembers are public
ser*defined value type
Can be allocated on the heap,
on the stac' or as a member5can be used as value or reference6
Always allocated on the stac' or
as a member
Members are always publicMembers can be public,internalor private
C"assesand StrctsC# Strcts vs C Strcts
4ery different from C22 struct
-
7/23/2019 Advanced C#.ppt
14/85
public class Car : e*icle {
public enu$ +a,e { -+ onda B+/ }
+a,e $a,e;
strin% vid;
!oint location;
Car(+a,e $ strin% vid; !oint loc) {
t*is.$a,e = $;
t*is.vid = vid;
t*is.location = loc;
}
public void Drive() {Console./rite"ine(0vroo$1); }
}
Car c = ne Car(Car.+a,e.B+/
02345567T681ne !oint(49));c.Drive();
C"asses and StrctsC"ass
-
7/23/2019 Advanced C#.ppt
15/85
public struct !oint { int x ; public !oint(int x int ) {
t*is.x = x;t*is. = ; } public int { %et { return x; } set { x = value; } } public int < { %et { return ; }
set { = value; } }}
!oint p = ne !oint(5);p. >= ?@@;int px = p.; AA px = ?@
C"asses and StrctsStrct
-
7/23/2019 Advanced C#.ppt
16/85
C"assesand StrctsStatic vs 8nstance Mem3ers
+y default, members are per instance Each instance gets its own fields
Methods apply to a specific instance Static members are per type
Static methods can7t access instance data
(o thisvariable in static methods
Don7t abuse static members )hey are essentially ob%ect*oriented
global data and global functions
-
7/23/2019 Advanced C#.ppt
17/85
C"asses and StrctsAccess Modifiers
Access modifiers specify who can use a type ora member
Access modifiers control encapsulation )op*level types 5those directly in a namespace6can be publicor internal
Class members can be public, private,
protected, internal, orprotected internal Struct members can be public, privateorinternal
-
7/23/2019 Advanced C#.ppt
18/85
8f the accessmodifier is
:hen a mem3er defined in type: and assem3"y A is accessi3"e
public to everyone
private within ) only 5the default6
protected to ) or types derived from )
internal to types within Aprotectedinternal
to ) or types derived from )or to types within A
C"asses and StrctsAccess Modifiers
-
7/23/2019 Advanced C#.ppt
19/85
C"asses and StrctsA3stract C"asses
An abstract class is one that cannot
be instantiated
Intended to be used as a base class
May contain abstract and non*abstract
function members
Similar to an interface
Cannot be sealed
-
7/23/2019 Advanced C#.ppt
20/85
C"asses and StrctsSea"ed C"asses
A sealed class is one that cannot be used as a
base class
Sealed classes can7t be abstract
All structs are implicitly sealed
1hy seal a class8 )o prevent unintended derivation
Code optimi/ation 4irtual function calls can be resolved at compile*time
-
7/23/2019 Advanced C#.ppt
21/85
class !erson { strin% na$e; public !erson(strin% na$e) { t*is.na$e = na$e; } public void Introduce(!erson p) { if (p = t*is) Console./rite"ine(0i I$ 0 > na$e); }}
C"asses and Strctst*is
)he this'eyword is a predefined variableavailable in non*static function members
sed to access data and function membersunambiguously
-
7/23/2019 Advanced C#.ppt
22/85
class #*ape { int x ; public override strin% To#trin%() { return x= > x > = > ; }
}class Circle : #*ape { int r; public override strin% To#trin%() { return base.To#trin%() > r= > r; }}
C"asses and Strctsbase
)he base'eyword is used to access classmembers that are hidden by similarly named
members of the current class
-
7/23/2019 Advanced C#.ppt
23/85
public class +Class { public const strin% version = 0?.@.@1; public const strin% s? = 0abc1 > 0def1;
public const int i4 = ? > ; public const double !IEI4 = i4 F +at*.!I; public const double s = +at*.#in(+at*.!I); AAGHHH ...}
C"asses and StrctsConstants
A constant is a data member that is evaluated at
compile*time and is implicitly static 5per type6
e-g- Math.PI
-
7/23/2019 Advanced C#.ppt
24/85
C"asses and Strcts&ie"ds
A field is a member variable
9olds data for a class or struct
Can hold: a class instance 5a reference6,
a struct instance 5actual data6, or
an array of class or struct instances
5an array is actually a reference6
-
7/23/2019 Advanced C#.ppt
25/85
C"asses and Strctseadon"y &ie"ds
Similar to a const, but is initiali/ed at
run*time in its declaration or in a constructor $nce initiali/ed, it cannot be modified
Differs from a constant Initiali/ed at run*time 5vs- compile*time6
Don7t have to re*compile clients
Can be static or per*instance
public class +Class { public static readonl double d? = +at*.#in(+at*.!I); public readonl strin% s?; public +Class(strin% s) { s? = s; } }
-
7/23/2019 Advanced C#.ppt
26/85
public class Button: Control { private strin% caption; public strin% Caption { %et { return caption; } set { caption = value;
Hepaint(); } }} Button b = ne Button();
b.Caption = J;#trin% s = b.Caption;
C"asses and Strcts;roperties
A property is a virtual field
"oo's li'e a field, but is implemented with code
Can beread*only,
write*only,
or readwrite
-
7/23/2019 Advanced C#.ppt
27/85
public class "istBox: Control { private strin%&' ite$s; public strin% t*is&int index' { %et { return ite$s&index'; }
set { ite$s&index' = value; Hepaint(); } }} "istBox listBox = ne "istBox();
listBox&@' = *ello;Console./rite"ine(listBox&@');
C"asses and Strcts8ndexers
An inde0er lets an instance behave as a
virtual array
Can be overloaded 5e-g- inde0 by intand by string6 Can be
read*only,
write*only,
or readwrite
-
7/23/2019 Advanced C#.ppt
28/85
C"asses and StrctsMethods
All code e0ecutes in a method Constructors, destructors and operators are special
types of methods
roperties and inde0ers are implemented with
getset methods
Methods have argument lists
Methods contain statements Methods can return a value
$nly if return type is not void
-
7/23/2019 Advanced C#.ppt
29/85
C"asses and StrctsMethod Arment ;assin
+y default, data is passed by value
A copy of the data is created and passed
to the method .or value types, variables cannot be modified by
a method call
.or reference types, the instance can be
modified by a method call, but the variable itself
cannot be modified by a method call
-
7/23/2019 Advanced C#.ppt
30/85
void Hef3unction(ref int p) { p>>;} int x = ?@;
Hef3unction(ref x);AA x is no ??
C"asses and StrctsMethod Arment ;assin
)he refmodifier causes arguments to bepassed by reference
Allows a method call to modify a variable 9ave to use refmodifier in method definition
and the code that calls it
4ariable has to have a value before call
-
7/23/2019 Advanced C#.ppt
31/85
void ut3unction(out int p){ p = ;}
int x;ut3unction(out x);AA x is no
C"asses and StrctsMethod Arment ;assin
)he outmodifier causes arguments to bepassed out by reference
Allows a method call to initiali/e a variable 9ave to use outmodifier in method definition
and the code that calls it
Argument has to have a value before returning
-
7/23/2019 Advanced C#.ppt
32/85
void !rint(int i);void !rint(strin% s);void !rint(c*ar c);void !rint(float f);int !rint(float f); AA Grror: duplicate si%nature
C"asses and Strcts2ver"oaded Methods
A type may overload methods, i-e- provide
multiple methods with the same name
Each must have a uni&ue signature Signature is based upon arguments only, the
return value is ignored
-
7/23/2019 Advanced C#.ppt
33/85
int #u$(para$s int&' intKrr) { int su$ = @;
foreac* (int i in intKrr) su$ >= i; return su$;}
int su$ = #u$(?4894L);
C"asses and Strcts;arameter Arrays
Methods can have a variable number of
arguments, called a parameter array
params'eyword declares parameter array Must be last argument
-
7/23/2019 Advanced C#.ppt
34/85
class 3oo { public void Do#o$et*in%(int i) {
... }} 3oo f = ne 3oo();
f.Do#o$et*in%();
C"asses and Strcts
-
7/23/2019 Advanced C#.ppt
35/85
C"asses and Strcts
-
7/23/2019 Advanced C#.ppt
36/85
class #*ape { public virtual void Dra() { ... }}class Box : #*ape {
public override void Dra() { ... }}class #p*ere : #*ape {public override void Dra() { ... }
}void andle#*ape(#*ape s) {
s.Dra(); ...} andle#*ape(ne Box());
andle#*ape(ne #p*ere());andle#*ape(ne #*ape());
C"asses and Strcts
-
7/23/2019 Advanced C#.ppt
37/85
C"asses and StrctsA3stract Methods
An abstract method is virtual and has no
implementation
Must belong to an abstract class Intended to be implemented in a derived class
-
7/23/2019 Advanced C#.ppt
38/85
abstract class #*ape { public abstract void Dra();}class Box : #*ape {
public override void Dra() { ... }}class #p*ere : #*ape {public override void Dra() { ... }
}void andle#*ape(#*ape s) {
s.Dra(); ...}
andle#*ape(ne Box());andle#*ape(ne #p*ere());andle#*ape(ne #*ape()); AA Grror
C"asses and StrctsA3stract Methods
-
7/23/2019 Advanced C#.ppt
39/85
C"asses and StrctsMethod
-
7/23/2019 Advanced C#.ppt
40/85
class Derived: Base { AA version ?
public virtual void 3oo() { Console./rite"ine(Derived.3oo);
}}
class Base { AA version ?}
C"asses and StrctsMethod
-
7/23/2019 Advanced C#.ppt
41/85
C"asses and StrctsConstrctors
Instance constructors are special methods that
are called when a class or struct is instantiated
erforms custom initiali/ation Can be overloaded
If a class doesn7t define any constructors, an
implicit parameterless constructor is created
Cannot create a parameterless constructor for
a struct All fields initiali/ed to /eronull
-
7/23/2019 Advanced C#.ppt
42/85
class B { private int *; public B() { } public B(int *) { t*is.* = *; }}class D : B { private int i; public D() : t*is(L) { } public D(int i) { t*is.i = i; } public D(int * int i) : base(*) { t*is.i = i; }}
C"asses and StrctsConstrctor 8nitia"i=ers
$ne constructor can call another with aconstructor initiali/er
Can call this(...)or base(...) Default constructor initiali/er is base()
-
7/23/2019 Advanced C#.ppt
43/85
C"asses and StrctsStatic Constrctors
A static constructor lets you create initiali/ation
code that is called once for the class
=uaranteed to be e0ecuted before the firstinstance of a class or struct is created and
before any static member of the class or struct is
accessed
(o other guarantees on e0ecution order $nly one static constructor per type
Must be parameterless
-
7/23/2019 Advanced C#.ppt
44/85
class 3oo { M3oo() {
Console./rite"ine(0Destroed {@}1 t*is);}
}
C"asses and Strcts!estrctors
A destructor is a method that is called before an
instance is garbage collected
sed to clean up any resources held by theinstance, do boo''eeping, etc-
$nly classes, not structs can have destructors
-
7/23/2019 Advanced C#.ppt
45/85
C"asses and Strcts!estrctors
nli'e C22, C# destructors are non*deterministic
)hey are not guaranteed to be called at a
specific time )hey are guaranteed to be called before
shutdown
se the usingstatement and the
Iisposableinterface to achieve deterministicfinali/ation
-
7/23/2019 Advanced C#.ppt
46/85
class Car { strin% vid; public static bool operator ==(Car x Car )
{ return x.vid == .vid; }}
C"asses and Strcts2perator 2ver"oadin
ser*defined operators
Must be a static method
-
7/23/2019 Advanced C#.ppt
47/85
C"asses and Strcts2perator 2ver"oadin
> N M
true false >> NN
$verloadable unary operators
$verloadable binary operators
> N F A M
O P Q R == =
SS S S= =
-
7/23/2019 Advanced C#.ppt
48/85
C"asses and Strcts2perator 2ver"oadin
(o overloading for member access, method
invocation, assignment operators, nor these
operators: si!eof, new, is, as, typeof,chec"ed, unchec"ed, ##, $$, and %&
)he ##and $$operators are automaticallyevaluated from #and $
$verloading a binary operator 5e-g- '6 implicitlyoverloads the corresponding assignment
operator 5e-g- '6
-
7/23/2019 Advanced C#.ppt
49/85
C"asses and Strcts2perator 2ver"oadin
struct ector { int x ; public ector(x ) { t*is.x = x; t*is. = ; } public static ector operator >(ector a ector b) { return ector(a.x > b.x a. > b.); }
...}
-
7/23/2019 Advanced C#.ppt
50/85
class Uote { int value; AA Convert to *ertV W no loss of precision public static i$plicit operator double(Uote x) { return ...; } AA Convert to nearest note
public static explicit operator Uote(double x) { return ...; }}
Uote n =(Uote)LL.598;double d = n;
C"asses and StrctsConversion 2perators
ser*defined e0plicit and implicit conversions
-
7/23/2019 Advanced C#.ppt
51/85
C"asses and Strcts8mp"ementin 8nterfaces
Classes and structs can implement multiple
interfaces
A class or struct that inherits from an interfacemust implement all function members defined in
that interface
-
7/23/2019 Advanced C#.ppt
52/85
public interface IDelete { void Delete();}public class TextBox : IDelete { public void Delete() { ... }}public class Car : IDelete { public void Delete() { ... }}
TextBox tb = ne TextBox();IDelete iDel = tb;iDel.Delete();
Car c = ne Car();iDel = c;
iDel.Delete();
C"asses and Strcts8mp"ementin 8nterfaces
-
7/23/2019 Advanced C#.ppt
53/85
public interface IDelete { void Delete();}public interface I3oo { void Delete();
}public class TextBox : IDelete I3oo { public void IDelete.Delete() { ... } public void I3oo.Delete() { ... }}
C"asses and Strcts8mp"ementin 8nterfaces
E0plicit interface implementation
9andles name collisions
-
7/23/2019 Advanced C#.ppt
54/85
C"asses and Strcts*ested :ypes
Declared within the scope of another type
(esting a type provides three benefits: (ested type can access all the members of its
enclosing type, regardless of access modifer (ested type can be hidden from other types Accessing a nested type from outside the enclosing
type re&uires specifying the type name
(ested types can be declared newto hideinherited types
nli'e ;ava inner classes, nested types imply norelationship between instances
-
7/23/2019 Advanced C#.ppt
55/85
C"asses and Strctsis2perator
)he isoperator is used to dynamically test if therun*time type of an ob%ect is compatible with a
given type
static void Do#o$et*in%(obXect o) { if (o is Car)
((Car)o).Drive();}
Don7t abuse the isoperator: it is preferable todesign an appropriate type hierarchy with
polymorphic methods
-
7/23/2019 Advanced C#.ppt
56/85
C"asses and Strctsas2perator
)he asoperator tries to convert a variable to aspecified type> if no such conversion is possible
the result is null
static void Do#o$et*in%(obXect o) { Car c = o as Car; if (c = null) c.Drive();}
More efficient than using isoperator: test andconvert in one operation
Same design warning as with the isoperator
-
7/23/2019 Advanced C#.ppt
57/85
C"asses and Strctstpeof2perator
)he typeofoperator returns the System.Typeob%ect for a specified type
Can then use reflection to dynamically obtaininformation about the type
Console./rite"ine(tpeof(int).3ullUa$e);Console./rite"ine(tpeof(#ste$.Int).Ua$e);
Console./rite"ine(tpeof(float).+odule);Console./rite"ine(tpeof(double).Is!ublic);Console./rite"ine(tpeof(Car).+e$berTpe);
-
7/23/2019 Advanced C#.ppt
58/85
!e"eates2verview
A delegate is a reference type that defines a
method signature
A delegate instance holds one or more methods Essentially an ?ob%ect*oriented function pointer@
Methods can be static or non*static
Methods can return a value
rovides polymorphism for individual functions
.oundation for event handling
-
7/23/2019 Advanced C#.ppt
59/85
!e"eates2verview
dele%ate double Del(double x); AA Declare
static void De$oDele%ates() { Del delInst = ne Del(+at*.#in); AAInstantiate
double x = delInst(?.@); AA Invo,e}
-
7/23/2019 Advanced C#.ppt
60/85
!e"eatesM"ticast !e"eates
A delegate can hold and invo'e multiple
methods Multicast delegates must contain only methods that
return void, else there is a run*time e0ception
Each delegate has an invocation list Methods are invo'ed se&uentially, in the order added
)he and *operators are used to add andremove delegates, respectively
and *operators are thread*safe
-
7/23/2019 Advanced C#.ppt
61/85
!e"eatesM"ticast !e"eates
dele%ate void #o$eGvent(int x int );static void 3oo?(int x int ) { Console./rite"ine(3oo?);
}static void 3oo(int x int ) { Console./rite"ine(3oo);}public static void +ain() { #o$eGvent func = ne #o$eGvent(3oo?); func >= ne #o$eGvent(3oo); func(?); AA 3oo? and 3oo are called func N= ne #o$eGvent(3oo?); func(4); AA nl 3oo is called}
-
7/23/2019 Advanced C#.ppt
62/85
!e"eatesand 8nterfaces
Could always use interfaces instead of delegates
Interfaces are more powerful
Multiple methods Inheritance
Delegates are more elegant for event handlers "ess code
Can easily implement multiple event handlers on oneclassstruct
-
7/23/2019 Advanced C#.ppt
63/85
Events2verview
Event handling is a style of programming where
one ob%ect 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 ?callbac'@ mechanism
-
7/23/2019 Advanced C#.ppt
64/85
Events2verview
Events are well suited for user*interfaces )he user does something 5clic's a button, moves a
mouse, changes a value, etc-6 and the program
reacts in response
Many other uses, e-g- )ime*based events
Asynchronous operation completed Email message has arrived
A web session has begun
-
7/23/2019 Advanced C#.ppt
65/85
Events2verview
C# has native support for events
+ased upon delegates
An event is essentially a field holding a delegate 9owever, public users of the class can only
register delegates )hey can only call and * )hey can7t invo'e the event7s delegate
Multicast delegates allow multiple ob%ects to
register with the same event
-
7/23/2019 Advanced C#.ppt
66/85
EventsExamp"e> Component6Side
Define the event signature as a delegate
Define the event and firing logic
public dele%ate void Gventandler(obXect senderGventKr%s e);
public class Button { public event Gventandler Clic,;
protected void nClic,(GventKr%s e) { AA T*is is called *en button is clic,ed if (Clic, = null) Clic,(t*is e); }}
-
7/23/2019 Advanced C#.ppt
67/85
EventsExamp"e> %ser6Side
Define and register an event handler
public class +3or$: 3or$ { Button o,Button;
static void ,Clic,ed(obXect sender GventKr%s e) { #*o+essa%e(= ne Gventandler(,Clic,ed); }}
-
7/23/2019 Advanced C#.ppt
68/85
Attri3tes2verview
It7s often necessary to associate information
5metadata6 with types and members, e-g- Documentation 3" for a class
)ransaction conte0t for a method
!M" persistence mapping
C$M rogID for a class
Attributes allow you to decorate a code element5assembly, module, type, member, return value
and parameter6 with additional information
-
7/23/2019 Advanced C#.ppt
69/85
Attri3tes2verview
&elpYrl(0*ttp:AA#o$eYrlAK!IDocsA#o$eClass1)'class #o$eClass {
&bsolete(0Yse #o$eUe+et*od instead1)' public void #o$eld+et*od() {...
}
public strin% Test(o$eKttr()' strin% para$?) { ...
}}
-
7/23/2019 Advanced C#.ppt
70/85
Attri3tes2verview
Attributes are superior to the alternatives Modifying the source language sing e0ternal files, e-g-, -ID", -DE.
Attributes are e0tensible Attributes allow to you add information not supported
by C# itself (ot limited to predefined information
+uilt into the -(E) .ramewor', so they wor'across all -(E) languages Stored in assembly metadata
-
7/23/2019 Advanced C#.ppt
71/85
Attri3tes2verview
Attri3te *ame !escription
+rowsableShould a property or event be displayed inthe property window
Seriali!able Allows a class or struct to be seriali/ed
,bsolete Compiler will complain if target is used
ProgId C$M rog ID
Transaction )ransactional characteristics of a class
Some predefined -(E) .ramewor' attributes
-
7/23/2019 Advanced C#.ppt
72/85
Attri3tes2verview
Attributes can be Attached to types and members E0amined at run*time using reflection
Completely e0tensible Simply a class that inherits from System.-ttribute
)ype*safe Arguments chec'ed at compile*time
E0tensive use in -(E) .ramewor' !M", 1eb Services, security, seriali/ation,
component model, C$M and Invo'e interop,code configuration
-
7/23/2019 Advanced C#.ppt
73/85
Attri3tes?eryin Attri3tes
&elpYrl(*ttp:AA#o$eYrlA+Class)'class Class? {}&elpYrl(*ttp:AA#o$eYrlA+Class)elpYrl(*ttp:AA#o$eYrlA+Class1 Ta%=0ctor1)'class Class {}
Tpe tpe = tpeof(+Class);foreac* (obXect attr in tpe.-etCusto$Kttributes() )
{ if ( attr is elpYrlKttribute ) { elpYrlKttribute *a = (elpYrlKttribute) attr; $Broser.Uavi%ate( *a.Yrl ); }
}
-
7/23/2019 Advanced C#.ppt
74/85
C# provides preprocessor directives that serve a
number of functions
nli'e C22, there is not a separate preprocessor )he ?preprocessor@ name is preserved only for
consistency with C22
C22 preprocessor features removed include:
include: (ot really needed with one*stopprogramming> removal results in faster compilation
Macro version of define: removed for clarity
;reprocessor !irectives2verview
-
7/23/2019 Advanced C#.ppt
75/85
;reprocessor !irectives2verview
!irective !escription
define, undef Define and undefine conditional symbols
if/elif, else, endif Conditionally s'ip sections of code
error, warning Issue errors and warnings
region, end Delimit outline regions
line Specify line number
-
7/23/2019 Advanced C#.ppt
76/85
Zdefine Debu%public class Debu% { &Conditional(Debu%)' public static void Kssert(bool cond #trin% s) {
if (cond) { t*ro ne KssertionGxception(s); } } void Do#o$et*in%() { ... AA If Debu% is not defined t*e next line is AA not even called Kssert((x == ) 0 s*ould e[ual
-
7/23/2019 Advanced C#.ppt
77/85
;reprocessor !irectivesAssertions
+y the way, assertions are an incredible way toimprove the &uality of your code
An assertion is essentially a unit test built right
into your code Bou should have assertions to test
preconditions, postconditions and invariants
Assertions are only enabled in debug builds
Bour code is A7d every time it runs
Must read: ?Writing Solid Code@, by SteveMaguire, Microsoft ress, IS+( *F**G
@M1 C
-
7/23/2019 Advanced C#.ppt
78/85
@M1 Comments2verview
rogrammers don7t li'e to document code, so we need a
way to ma'e it easy for them to produce &uality,
up*to*date documentation
C# lets you embed !M" comments that document types,members, parameters, etc- Denoted with triple slash: 000
!M" document is generated when code is compiled
with 0docargument Comes with predefined !M" schema, but you can add
your own tags too Some are verified, e-g- parameters, e0ceptions, types
@M1 C t
-
7/23/2019 Advanced C#.ppt
79/85
@M1 Comments2verview
@M1 :a !escription
Ssu$$ar Sre$ar,s :ype or mem3er
Spara$ Method parameter
Sreturns Method retrn va"e
Sexception Exceptions thrown from method
Sexa$ple Sc Scode Samp"e code
Ssee Sseealso Cross references
Svalue ;roperty
Spara$ref %se of a parameter
Slist Site$ ... &ormattin hints
Sper$ission ;ermission reirements
@M1 C t
-
7/23/2019 Advanced C#.ppt
80/85
class $lGle$ent { AAA Ssu$$ar AAA Heturns t*e attribute it* t*e %iven na$e and AAA na$espaceSAsu$$ar AAA Spara$ na$e=na$e AAA T*e na$e of t*e attributeSApara$ AAA Spara$ na$e=ns AAA T*e na$espace of t*e attribute or null if AAA t*e attribute *as no na$espaceSApara$ AAA Sreturn AAA T*e attribute value or null if t*e attribute AAA does not existSAreturn AAA Sseealso cref=-etKttr(strin%)A AAA public strin% -etKttr(strin% na$e strin% ns) { ... }}
@M1 Comments2verview
% f C d
-
7/23/2019 Advanced C#.ppt
81/85
%nsafe Code2verview
Developers sometime need total control erformance e0tremes Dealing with e0isting binary structures E0isting code Advanced C$M support, D"" import
C# allows you to mar' code as unsafe, allowing ointer types, pointer arithmetic *1, 'operators nsafe casts (o garbage collection
% f C d
-
7/23/2019 Advanced C#.ppt
82/85
unsafe void 3oo() { c*arF buf = stac,alloc c*ar&5\'; for (c*arF p = buf; p S buf > 5\; p>>) Fp =@; ...}
%nsafe Code2verview
"ets you embed native CC22 code
+asically ?inline C@
Must ensure the =C doesn7t move your data se fi2edstatement to pin data se stac"allocoperator so memory is allocated
on stac', and need not be pinned
% f C d
-
7/23/2019 Advanced C#.ppt
83/85
class 3ile#trea$: #trea$ { int *andle;
public unsafe int Head(bte&' buffer int indexint count) {
int n = @; fixed (bteF p = buffer) { Head3ile(*andle p > index count Pn null); } return n; }
&dlli$port(,ernel4 #et"astGrror=true)' static extern unsafe bool Head3ile(int *3ile voidF lpBuffer int nBtesToHead intF nBtesHead verlappedF lpverlapped);}
%nsafe Code2verview
% f C d
-
7/23/2019 Advanced C#.ppt
84/85
%nsafe CodeC# and ;ointers
ower comes at a priceH nsafe means unverifiable code
Stricter security re&uirements +efore the code can run
Downloading code
-
7/23/2019 Advanced C#.ppt
85/85
More esorces
*ttp:AA$sdn.$icrosoft.co$
*ttp:AAindos.oreill.co$AnesA*eXlsber%E@8@@.*t$l
*ttp:AA.cs*arp*elp.co$A
*ttp:AA.cs*arpNstation.co$A
*ttp:AA.cs*arpindex.co$A *ttp:AA$sdn.$icrosoft.co$A$sdn$a%AissuesA@6@@Acs*arpAcs*
arp.asp
*ttp:AA.*it$ill.co$Apro%ra$$in%AdotUGTAcs*arp.*t$l
*ttp:AA.cNs*arpcorner.co$A
*ttp:AA$sdn.$icrosoft.co$AlibrarAdefault.asp]YH"=AlibrarAdotnetAcsspecAvclrfcs*arpspecE#tart.*t$