Your SlideShare is downloading. ×
0
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Csharp In Detail Part2
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Csharp In Detail Part2

2,980

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,980
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
347
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • ACCU Spring Conference, Christ Church College, Oxford, Friday 30 th March 2001. { JSL } Jagger Software Limited http://www.jaggersoft.com Tel . +44 (0) 1823 354 192 Hi, I'm Jon Jagger, a freelance software trainer, designer, and consultant. I specialise in curly bracket languages, hence { JSL }. In a former life I was QA Training's C++ and C product consultant. I'm an UK C++ standards panel member and a regular contributor to the ACCU Overload journal. I'm married with three increasingly larger children. My interests include training excellence, design, problem solving, and monty python (which should be required knowledge for all software developers). Forget the technical interview, just recite the parrot sketch. I don't really know what else to say in a short bio such as this. I'm very very good at sleeping. And breathing. Both of which I practice a lot.
  • Transcript

    • 1. C# in Detail Jon Jagger Software Trainer, Designer, Consultant www.jaggersoft.com jon @ jaggersoft.com { JSL } Part 2
    • 2. Blatant Advert <ul><li>an interactive, friendly, expert instructor </li></ul><ul><ul><li>Jon has worked for Microsoft using C# </li></ul></ul><ul><li>lots of great exercises </li></ul><ul><ul><li>to make sure you understand </li></ul></ul><ul><li>even more slides </li></ul><ul><ul><li>with detail, explanations, and rationales </li></ul></ul><ul><li>full slide notes </li></ul><ul><ul><li>include careful comparisons with C++ and Java </li></ul></ul>C# in Detail is also available as an instructor led course
    • 3. Agenda <ul><li>string </li></ul><ul><li>class </li></ul><ul><li>constructors </li></ul><ul><li>fields </li></ul><ul><li>parameters </li></ul><ul><li>arrays </li></ul><ul><li>boxing </li></ul><ul><li>exceptions </li></ul><ul><li>garbage collection </li></ul><ul><li>inheritance, interfaces, abstract classes </li></ul><ul><li>nested types </li></ul><ul><li>delegates and events </li></ul><ul><li>namespaces </li></ul><ul><li>assemblies </li></ul><ul><li>attributes </li></ul><ul><li>reflection </li></ul>
    • 4. string C# Programming Fundamentals Objects Relationships Systems
    • 5. string Type <ul><li>string is a reference type </li></ul><ul><ul><li>the only one with a literal syntax </li></ul></ul><ul><ul><li>immutable; just like in Java </li></ul></ul>s stack heap null @ t static void Main() { string s = null ; string t = &quot;Hiker&quot; ; ... t[0] = 'B' ; } Hiker compile time error
    • 6. indexer <ul><li>string has a readonly indexer </li></ul><ul><ul><li>integer index is always bounds checked </li></ul></ul><ul><ul><li>throws ArgumentOutOfRangeException </li></ul></ul>static void Func( string s) { for ( int i = 0; i != s.Length; i++) { char c = s[i]; Console.Write(c); } }
    • 7. System.String <ul><li>string is an alias for System.String </li></ul>namespace System { public sealed class String ... { ... // static methods public static int Compare( string , string ); public static bool Equals( string , string ); public static string Format( string , params object []); ... // readonly property public int Length { get; } // readonly indexer public char this [ int index] { get; } // instance methods public int CompareTo( string ); public override bool Equals( object ); public new bool Equals( string ); ... } }
    • 8. StringBuilder <ul><li>System.Text.StringBuilder </li></ul>namespace System.Text { public sealed class StringBuilder { public StringBuilder(); // read-write properties public int Length { get ; set ; } public int Capacity { get ; set ; } // read-write indexer public char this [ int index] { get ; set ; } // instance methods public StringBuilder Append(...); public StringBuilder Insert(...); public StringBuilder Remove( int , int ); public StringBuilder Replace(...); ... public override string ToString(); } }
    • 9. string Literals <ul><li>usual syntax </li></ul><ul><ul><li>embedded escape chars, but no octal </li></ul></ul><ul><li>unusual syntax </li></ul><ul><ul><li>@ verbatim string literals </li></ul></ul>&quot;c: emp&quot; @&quot;c: emp&quot; @&quot;quote&quot;&quot; char&quot; @&quot; MP: we got a slug JC: does it talk? MP: yup JC: I'll have it&quot; c: emp c: emp quote&quot;char MP: we got a slug JC: does it talk? MP: yup JC: I'll have it
    • 10. string Operators <ul><li>equality operators are overloaded </li></ul><ul><ul><li>they compare the values not the references </li></ul></ul><ul><ul><li>relational operators are not overloaded </li></ul></ul><ul><li>binary + is overloaded, forwards to .Concat </li></ul><ul><ul><li>operator += too </li></ul></ul>IsTrue(s == t); IsTrue(s.Equals(t)); IsFalse(( object )s == ( object )t); s stack heap @ @ t Hiker Hiker IsTrue(s == t); IsTrue(s.Equals(t)); IsTrue(( object )s == ( object )t); s @ @ t Hiker
    • 11. class C# Programming Fundamentals Objects Relationships Systems
    • 12. class Declaration <ul><li>a user-defined reference type </li></ul>class Pair { public int X, Y; }; optional semi-colon by convention public names start with an uppercase letter (PascalCasing) class Pair { private int x, y; } ...and private names start with a lowercase letter (camelCasing) class Pair { int x, y; } default access is private
    • 13. object Creation <ul><li>a class local variable lives on the stack </li></ul><ul><ul><li>is not definitely assigned </li></ul></ul><ul><ul><li>can be initialised with null or a c'tor call </li></ul></ul>p stack ? .X .Y heap required static void Main() { Pair p; } static void Main() { Pair p = null ; } static void Main() { Pair p = new Pair(); } p null p @ 0 0
    • 14. class Constructor <ul><li>usual class rules </li></ul><ul><ul><li>compiler declares a default c'tor </li></ul></ul><ul><ul><li>you can declare the default c'tor </li></ul></ul><ul><ul><li>if you declare a c'tor the compiler doesn't </li></ul></ul>class Pair { } you declare a default c'tor class Pair { public Pair( int x, int y) {...} } compiler declares a default c'tor class Pair { public Pair() { ... } } no one declares a default c'tor
    • 15. : this(...) <ul><li>a c'tor can call a sibling c'tor </li></ul><ul><ul><li>syntax is a cross between C++ and Java </li></ul></ul><ul><ul><li>no general member-init-list syntax though </li></ul></ul>class Point { public Point( int x, int y) : this (x, y, Colour.Red) { } public Point( int x, int y, Colour c) { ... } ... private int x, y; private Colour c; }
    • 16. instance Fields <ul><li>instance fields... </li></ul><ul><ul><li>are default initialised by default in all c'tors </li></ul></ul><ul><ul><li>can be initialised in variable initialiser </li></ul></ul><ul><ul><li>can be explicitly initialised in a c'tor </li></ul></ul>class Point { public Point( int x, int y) { this .x = x; y = y; } ... private int x; private int y = 42; } no warning! OK OK OK
    • 17. readonly Fields <ul><li>readonly instance fields... </li></ul><ul><ul><li>are instance fields that cannot be assigned to </li></ul></ul>compile time errors class Pair { public Pair( int x, int y) { this .x = x; this .y = y; } public void Reset() { x = 0; y = 0; } private readonly int x, y; } this declares Pair as an immutable object
    • 18. const Fields <ul><li>const fields are implicitly static </li></ul><ul><ul><li>only simple types, enum s, & string can be const </li></ul></ul><ul><ul><li>const fields require a variable initializer </li></ul></ul>class Pair { private const int x = 0, y = 0; } class BadFields { ... BadFields(...) { question = 9 * 6; } ... static const int answer = 42; ... const int question; ... const Pair origin = new Pair(); } OK compile time errors this declares Pair with no instance fields
    • 19. static Fields <ul><li>to declare static fields of other types </li></ul><ul><ul><li>use static keyword ! </li></ul></ul><ul><ul><li>static fields are default initialised </li></ul></ul><ul><ul><li>static fields can use variable initialisers </li></ul></ul><ul><ul><li>access is via typename only </li></ul></ul>class Pair { ... static Pair origin; ... static Pair topLeft = new Pair(10,20); ... static AnyClass field; ... static string both = &quot;Arthur&quot;; } Pair p = new Pair(); ... F(p.Origin); // compile-time error F(Pair.Origin); // OK
    • 20. static Constructor <ul><li>a static c'tor initialises the type </li></ul><ul><ul><li>can initialize static fields but not const fields </li></ul></ul><ul><ul><li>called by VES when the type is loaded </li></ul></ul><ul><ul><li>cannot be called, no access modifier allowed </li></ul></ul>class GoodExample { static GoodExample() { origin = new Pair(0,0); } ...static readonly Pair origin; } OK class BadExample { public static GoodExample() { x = 42; } ...const int x; } compile time errors
    • 21. Copy Parameters <ul><li>a plain parameter is a copy of the argument </li></ul><ul><ul><li>no frills bitwise copy </li></ul></ul><ul><ul><li>the argument must be definitely assigned </li></ul></ul><ul><ul><li>argument can be an &quot;rvalue&quot; </li></ul></ul>static void Method(Pair parameter) { parameter = new Pair(42,42); } static void Main() { Pair arg = new Pair(0,0); Console.WriteLine(arg.X); Method(arg); Console.WriteLine(arg.X); } 0 0
    • 22. ref Parameters <ul><li>a ref parameter is an alias for the argument </li></ul><ul><ul><li>no copy takes place </li></ul></ul><ul><ul><li>argument must be definitely assigned </li></ul></ul><ul><ul><li>argument must be an &quot;lvalue&quot; </li></ul></ul><ul><ul><li>ref required on argument and parameter </li></ul></ul>static void Method( ref Pair parameter) { parameter = new Pair(42,42); } static void Main() { Pair arg = null ; //Console.WriteLine(p.X); Method( ref arg); Console.WriteLine(arg.X); } 42 Method( ref type [ ] array ) allowed
    • 23. out Parameters <ul><li>an out parameter is an alias for the argument </li></ul><ul><ul><li>no copy takes places </li></ul></ul><ul><ul><li>argument need not be definitely assigned </li></ul></ul><ul><ul><li>parameter must be definitely assigned </li></ul></ul><ul><ul><li>argument must be an &quot;lvalue&quot; </li></ul></ul><ul><ul><li>out required on argument and parameter </li></ul></ul>static void Method( out Pair parameter) { parameter = new Pair(42,42); } static void Main() { Pair arg; //Console.WriteLine(p.X); Method( out arg); Console.WriteLine(arg.X); } 42 Method( out type [ ] array ) allowed
    • 24. in Parameters? <ul><li>readonly , const, and in , are all C# keywords </li></ul><ul><ul><li>they cannot be applied to parameters </li></ul></ul><ul><ul><li>reference types always grant write access </li></ul></ul>argument parameter optional required Copy ref out @ @ @ @ @@ @@ 0 0 initialize
    • 25. [ ] Arrays C# Programming Fundamentals Objects Relationships Systems
    • 26. Array Variables <ul><li>C# supports rectangular arrays </li></ul><ul><ul><li>rectangular arrays are reference types </li></ul></ul>int [] row = null ; int [,] grid = null ; int [,,] threeD = null ; row stack heap null null grid
    • 27. Array Instances <ul><li>array instances are created using new </li></ul><ul><ul><li>rectangular arrays must specify all dimensions </li></ul></ul><ul><ul><li>array instance elements are default initialised </li></ul></ul>int [] row = new int [4]; int [,] grid = new int [2,3]; row stack heap @ @ grid 0 0 0 0 0 0 0 0 0 0 array of struct s
    • 28. Array Initialisation <ul><li>arrays can be initialised </li></ul><ul><ul><li>omitted initialisers are not permitted </li></ul></ul><ul><ul><li>array size may be omitted </li></ul></ul><ul><ul><li>standard shortcut notation </li></ul></ul>int [] row = new int [4] {1,2,3,4}; int [,] grid = new int [,] { {1,2,3}, {4,5,6,}, }; int [,] shortcut = { {1,2,3}, {4,5,6} }; row stack heap @ @ grid 1 2 3 4 1 2 3 4 5 6 trailing commas are permitted
    • 29. System.Array <ul><li>all array types inherit from System.Array </li></ul>namespace System { public class Array { protected Array(); ... // readonly properties public int Length { get; } public int Rank { get; } // instance methods public int GetLength( int ); // static methods public static void Clear(Array, int , int ); ... } } int [,] cosmic = { {1,2,3}, {4,5,6} }; Console.Write(cosmic.Length); Console.Write(cosmic.Rank); Console.Write(cosmic.GetLength(0)); Console.Write(cosmic.GetLength(1)); 6223
    • 30. Using Arrays <ul><li>all array access is bounds checked </li></ul><ul><ul><li>throws IndexOutOfRangeException </li></ul></ul>class Example { static void Use( int [,] grid) { int rowLength = grid.GetLength(0); int colLength = grid.GetLength(1); for (int row = 0; row != rowLength; row++) { for (int col = 0; col != colLength; col++) { Console.WriteLine(grid[row,col]); } } } static void Main() { Use( new int [,]{ {1,2,3}, {4,5,6} }); ... } } there is no direct way to make rowLength constant
    • 31. Ragged Arrays <ul><li>C# also supports ragged arrays </li></ul><ul><ul><li>arrays of arrays </li></ul></ul><ul><ul><li>array instance still created using new </li></ul></ul>int [][] ragged = new int [3][ ]; int [][][] tatters = null ; ragged stack heap @ null null null tatters null
    • 32. Ragged Initialisation <ul><li>each sub array can be intialised as before </li></ul><ul><ul><li>you can only specify the first dimension </li></ul></ul>int [][] ragged = new int [3][4]; int [][] ragged = new int [3][] { new int [2], null , new int [4]{ 1, 2, 3, 4 } }; ragged stack heap @ @ null @ 0 0 1 2 3 4 { ... } shorthand allowed here but not here compile time error
    • 33. params type[ ] <ul><li>C# supports variadic functions </li></ul><ul><ul><li>params keyword can be used on array parameter </li></ul></ul><ul><ul><li>only on a single dimension array parameter </li></ul></ul>static void GreyHole( params int [] row) { if (row != null ) Console.WriteLine(row.Length); else Console.WriteLine( &quot;null&quot; ); } static void Main() { GreyHole( null ); GreyHole(); GreyHole(1); GreyHole( new int []{1, 2}); GreyHole(1,2,3); } null 0 1 2 3 params is not part of the signature
    • 34. params object[ ] <ul><li>params with object as the element type </li></ul><ul><ul><li>creates a truly variadic function </li></ul></ul><ul><ul><li>thanks to boxing </li></ul></ul>static void BlackHole( params object [] row) { if (row != null ) Console.WriteLine(row.Length); else Console.WriteLine( &quot;null&quot; ); } static void Main() { BlackHole( null ); BlackHole(); BlackHole(1M); BlackHole( new int []{1,2}); BlackHole(1, 2.0, &quot;three&quot; ); } null 0 1 1 3
    • 35. Array Notes int [ ] illegal[ , ]; class Base {...} class Derived : Base {...} Derived[] ds = new Derived[]{...}; Base[] bs = ds; unsafe { int * array = stackalloc int [42]; ... } only one syntax C# supports array covariance you can create an array on the stack, but only in unsafe code object o = new int [42]; arrays are reference types int [ ][ , ] mixed; you can mix the two kinds of arrays
    • 36. Boxing C# Programming Fundamentals Objects Relationships Systems
    • 37. Recap <ul><li>value types </li></ul><ul><ul><li>variables contain their own data directly </li></ul></ul><ul><ul><li>local variables always live on the stack </li></ul></ul><ul><li>reference types </li></ul><ul><ul><li>variables refer to their data indirectly </li></ul></ul><ul><ul><li>local variables refer to objects on the heap </li></ul></ul>object value enum class interface [ ]array delegate struct value object object object @ @ @ @
    • 38. struct vs class struct Pair { int x, y; ... } Pair p = new Pair(1,2); Pair copy = p; p.x stack heap class Pair { int x, y; ... } Pair p = new Pair(1,2); Pair copy = p; 1 2 @ p @ copy 1 2 p.y copy.x copy.y .x 1 2 .y
    • 39. Objects Everywhere <ul><li>everything implicitly inherits from object </li></ul><ul><ul><li>arrays, class es, interface s, delegate s </li></ul></ul><ul><ul><li>struct s, enum s, as well ! </li></ul></ul>System.Int32 « struct » System.ValueType « class » System.Enum « class » Suit « enum » Pair « struct » System.Object « class » int == System.Int32
    • 40. Problem? <ul><li>a reference can bind to a value </li></ul><ul><ul><li>does the reference refer into the stack? </li></ul></ul><ul><ul><li>if so what happes when the scope ends? </li></ul></ul>struct Pair { public int X, Y; ... } class Example { static object Dangle() { Pair p = new Pair(1,2); object o = p; return o; } static void Main() { object o = Dangle(); ... } } p.X stack 1 2 @ o p.Y ?
    • 41. Boxed Solution <ul><li>when a reference variable binds to a value </li></ul><ul><ul><li>the runtime copies the value onto the heap </li></ul></ul><ul><ul><li>the reference refers to the copy on the heap </li></ul></ul><ul><ul><li>this is called boxing </li></ul></ul>the copy is the same plain bitwise copy used for value parameters/returns struct Pair { public int X, Y; ... } static void Function() { Pair p = new Pair(1,2); object o = p; } p.X stack heap 1 2 p.Y .X 1 2 .Y @ o box
    • 42. Unboxing <ul><li>unboxing copies the boxed value back again </li></ul><ul><ul><li>this requires an explicit cast to exact type </li></ul></ul><ul><ul><li>if the target type is wrong - InvalidCastException </li></ul></ul>struct Pair { public int X, Y; ... } static void Function() { Pair p = new Pair(1,2); object o = p; p.X = p.Y = 0; Pair q = (Pair)o; } p.X stack heap 0 0 p.Y .X 1 2 .Y @ o cast q.X 1 2 q.Y box unbox
    • 43. System.Object <ul><li>object is an alias for System.Object </li></ul>namespace System { public class Object { public Object(); public virtual bool Equals( object ); public virtual int GetHashCode(); public Type GetType(); public virtual string ToString(); ... } } static void AnySingleArgument( object accepted) { ... } any value variable (implicit boxing) any reference variable (implicit conversion)
    • 44. No Overhead <ul><li>in fact, value types do not derive from object </li></ul><ul><ul><li>each value type has a hidden reference type </li></ul></ul><ul><ul><li>the hidden reference type holds the boxed value </li></ul></ul><ul><ul><li>object virtual method are not override n in values </li></ul></ul><ul><ul><li>they are override n in the hidden reference type </li></ul></ul>Pair « struct » Object « class » Pair Reference « class » Int32 Reference « class » Int32 « struct » 42.ToString() is not a virtual call 1 1
    • 45. Inheritance C# Programming Fundamentals Objects Relationships Systems
    • 46. Extension <ul><li>like Java... </li></ul><ul><ul><li>a class can inherit from a single base class </li></ul></ul><ul><ul><li>all inheritance is implicitly public </li></ul></ul><ul><li>unlike Java... </li></ul><ul><ul><li>there is no extends keyword </li></ul></ul><ul><ul><li>by default methods are not virtual </li></ul></ul><ul><ul><li>a struct cannot inherit from a struct or class * </li></ul></ul>ViolinPlayer « class » Musician « class » class Musician { public void NotVirtual()... } class ViolinPlayer : Musician { ... }
    • 47. : base(...) <ul><li>a class can call a sibling constructor </li></ul><ul><ul><li>a struct can too </li></ul></ul><ul><li>a class can call its base class constructor </li></ul><ul><ul><li>a struct can't (since it can't have a base class ) </li></ul></ul>class Musician { public Musician( string name)... public void NotVirtual()... } class ViolinPlayer : Musician { public ViolinPlayer( string name) : base (name) { ... } }
    • 48. Method Access <ul><li>two restrictions </li></ul><ul><ul><li>a private method cannot be virtual </li></ul></ul><ul><ul><li>a struct can't declare a protected member </li></ul></ul>class GoodClass { public virtual void Alpha()... protected virtual void Beta()... private void Gamma()... } class BadClass { private virtual void Delta()... } struct GoodStruct { public void Alpha()... private void Gamma()... } struct BadStruct { protected void Beta()... }
    • 49. virtual Methods <ul><li>a virtual method... </li></ul><ul><ul><li>introduces a method implementation </li></ul></ul><ul><ul><li>cannot be declared in a struct </li></ul></ul>class Musician { ... public virtual void TuneUp() { ... } } class ViolinPlayer : Musician { public virtual void TuneUp() { ... } } this does not override TuneUp from the Musician class
    • 50. override Methods <ul><li>an override method... </li></ul><ul><ul><li>specialises an inherited identical virtual method </li></ul></ul><ul><ul><li>is implicitly virtual itself </li></ul></ul><ul><ul><li>cannot be declared in a struct * </li></ul></ul>class Musician { ... public virtual void TuneUp() { ... } } class ViolinPlayer : Musician { public override void TuneUp() { ... } } this does same access too
    • 51. sealed Methods <ul><li>a sealed override method... </li></ul><ul><ul><li>specialises an inherited identical virtual method </li></ul></ul><ul><ul><li>which cannot itself be override n </li></ul></ul><ul><ul><li>cannot be declared in a struct </li></ul></ul>class Musician { ... public virtual void TuneUp() { ... } } class ViolinPlayer : Musician { public sealed override void TuneUp() { ... } } sealed is always used with override
    • 52. new Methods <ul><li>a new method... </li></ul><ul><ul><li>hides an identical inherited method </li></ul></ul><ul><ul><li>can be used in combination with virtual </li></ul></ul><ul><ul><li>cannot be used in combination with override </li></ul></ul>class Musician { ... public virtual void TuneUp() { ... } } class ViolinPlayer : Musician { public new virtual void TuneUp() { ... } }
    • 53. Table <ul><li>method modifiers </li></ul>struct class override no* yes sealed no yes new no* yes public yes yes protected no yes private yes yes virtual no yes only needed when overriding or hiding methods from System.ValueType
    • 54. Interfaces C# Programming Fundamentals Objects Relationships Systems
    • 55. interface <ul><li>interfaces contain method signatures </li></ul><ul><ul><li>no access modifier, implicitly public </li></ul></ul><ul><ul><li>no fields, not even static ones </li></ul></ul>interface names should start with an I interface ITuneable { void TuneUp(); } interface IPluckable { void Pluck(); } IPluckable « interface » ITuneable « interface »
    • 56. Multiple Interfaces <ul><li>a class can implement many interface s </li></ul><ul><ul><li>so can an interface </li></ul></ul><ul><ul><li>so can a struct (boxing) </li></ul></ul><ul><li>no implements keyword </li></ul><ul><ul><li>notation is positional </li></ul></ul><ul><ul><li>base class first, then base interface s </li></ul></ul>class Violin : Instrument , IPluckable , ITuneable { ... } IPluckable « interface » ITuneable « interface » Violin « class » Instrument « class »
    • 57. I.I.I. <ul><li>&quot;implicit&quot; interface implementation </li></ul><ul><ul><li>methods must be explicitly declared public </li></ul></ul><ul><ul><li>by default methods are not virtual </li></ul></ul>a class must implement all inherited interface methods interface ITuneable { void TuneUp(); } interface IPluckable { void Pluck(); } class Violin : IPluckable, ITuneable { public void TuneUp() { ... } public virtual void Pluck() { ... } ... }
    • 58. E.I.I. <ul><li>explicit interface implementation </li></ul><ul><ul><li>cannot have access modifier ( private -ish) </li></ul></ul><ul><ul><li>cannot be virtual </li></ul></ul>interface ITuneable { void TuneUp(); } interface IPluckable { void Pluck(); } class Violin : Instrument , IPluckable, ITuneable { void ITuneable.TuneUp() { ... } void IPluckable.Pluck() { ... } ... } consider inheriting two operations with the same signature you can mix III and EII
    • 59. interface Property <ul><li>an interface can declare a property </li></ul><ul><ul><li>readwrite, readonly, writeonly </li></ul></ul>interface IButton { string Caption { get ; set ; } ... } class Button : IButton { public virtual string Caption { get { ... } set { ... } } ... private string caption; }
    • 60. interface Indexer <ul><li>an interface can declare an indexer </li></ul><ul><ul><li>readwrite, readonly, writeonly </li></ul></ul><ul><ul><li>indexers are not static operators </li></ul></ul>interface IDictionary { string this [ string word ] { get ; set ; } ... } class Dictionary : IDictionary { public virtual string this [ string word ] { get { ... } set { ... } } ... }
    • 61. is <ul><li>use is operator to check for type support </li></ul><ul><ul><li>returns true or false </li></ul></ul><ul><ul><li>a cast can throw an InvalidCastException </li></ul></ul>static void GreyHole( object o) { if (o is IPluckable) { IPluckable ip = (IPluckable)o; ip.Pluck() ... } } static void Main() { GreyHole( new Violin()); GreyHole(42); } check once check twice cast
    • 62. as <ul><li>the as operator is similar </li></ul><ul><ul><li>performs the conversion if the type is supported </li></ul></ul><ul><ul><li>returns null if its not </li></ul></ul>static void GreyHole( object o) { IPluckable ip = o as IPluckable; if (ip != null ) { ip.Pluck(); ... } } static void Main() { GreyHole( new Violin()); GreyHole(42); } check once
    • 63. typeof <ul><li>retrieving the exact type of an object </li></ul><ul><ul><li>System.Object.GetType() for variables </li></ul></ul><ul><ul><li>typeof for types known at compile time </li></ul></ul><ul><ul><li>Type.GetType() for types known at runtime </li></ul></ul>static void Main() { Violin stradi = new Violin(); IPluckable ip = stradi; Type t1 = ip.GetType(); Type t2 = typeof (Violin); Type t3 = Type.GetType( &quot;Violin&quot; ); Console.WriteLine(t1 == t2); Console.WriteLine(t2 == t3); Console.WriteLine(( object )t1 == ( object )t2); Console.WriteLine(( object )t2 == ( object )t3); } True True True True
    • 64. ref out <ul><li>interface parameters </li></ul><ul><ul><li>can be ref qualified </li></ul></ul><ul><ul><li>can be out qualified </li></ul></ul>interface IPluckable { void Pluck(); } static void Replace( ref IPluckable instrument) { instrument = new Guitar(); } static void Create( out IPluckable instrument) { instrument = new Banjo(); }
    • 65. Table <ul><li>method modifiers </li></ul>struct class override no* yes sealed no yes new no* yes public yes yes protected no yes private yes yes virtual no yes i'face no no yes no no no no
    • 66. Abstract Classes C# Programming Fundamentals Objects Relationships Systems
    • 67. abstract Classes <ul><li>an abstract class ... </li></ul><ul><ul><li>cannot be instantiated </li></ul></ul><ul><ul><li>can extend an abstract class or a class </li></ul></ul><ul><ul><li>otherwise the same as a class </li></ul></ul>abstract class Bar { ... private int instanceMethod() { ... } private int instanceField; } abstract class Foo : Bar { ... public static int StaticMethod() { ... } public static int StaticField; }
    • 68. abstract Methods <ul><li>an abstract method... </li></ul><ul><ul><li>can only be declared in an abstract class </li></ul></ul><ul><ul><li>has no body </li></ul></ul><ul><ul><li>cannot be private </li></ul></ul>abstract class Foo : Bar { public abstract void Method(); ... }
    • 69. abstract Notes <ul><li>an abstract method... </li></ul><ul><ul><li>can override a inherited virtual method </li></ul></ul><ul><ul><li>must be implemented with the same access </li></ul></ul>abstract class Bar { protected virtual void Method() { ... } ... } abstract class Foo : Bar { protected abstract override void Method(); ... }
    • 70. sealed Classes <ul><li>a sealed class </li></ul><ul><ul><li>cannot be derived from </li></ul></ul><ul><ul><li>cannot declare virtual methods </li></ul></ul><ul><ul><li>cannot declare abstract methods </li></ul></ul><ul><ul><li>struct s and enum s are implicitly sealed </li></ul></ul>abstract class Foo : Bar { protected abstract Method(); } sealed class Wibble : Foo { protected override void Method() { ... } ... }
    • 71. Table <ul><li>method modifiers </li></ul>struct class override no* yes sealed no yes new no* yes public yes yes protected no yes private yes yes virtual no yes i'face no no yes no no no no abstract yes yes yes yes yes no yes sealed yes yes yes yes yes yes no abstract no no no yes no
    • 72. Another Table <ul><li>method modifier combinations </li></ul>override new sealed virtual 1 2 N N abstract • abstract N 3 N • virtual • N 4 override • N new • sealed modifier order is not significant
    • 73. Exceptions C# Programming Fundamentals Objects Relationships Systems
    • 74. System.Exception <ul><li>the root of all Exception clasases </li></ul>namespace System { public class Exception ... { public Exception(); public Exception( string ); public Exception( string , Exception); ... public Exception InnerException { get ; } public virtual string Message { get ; } public virtual string StackTrace { get ; } ... public override string ToString(); ... } }
    • 75. Hierarchy Exception ArithmeticException InvalidCastException DivideByZeroException OutOfMemoryException NullReferenceException OverflowException SystemException ... ExecutionEngineException IndexOutOfRangeException
    • 76. throw <ul><li>you can throw any object you like </li></ul><ul><ul><li>as long as it's derived from System.Exception </li></ul></ul>class Matrix { public Matrix( int rowSize, int colSize) { ... } public Row this [ int index ] { get { BoundsCheck(index); ... } set { BoundsCheck(index); ... } } // validation private void BoundsCheck( int index) { if (index < 0 || index >= rows.Length) throw new IndexOutOfRangeException(); } // representation private Row[] rows; } don't forget the new
    • 77. try catch <ul><li>you can separate out error handling code </li></ul><ul><ul><li>in a catch { block } after a try { block } </li></ul></ul><ul><ul><li>goodbye HRESULT </li></ul></ul>try { FileInfo source = new FileInfo(filename); int length = ( int )source.Length; char [] contents = new char [length]; ... } catch (SecurityException caught) { ... } catch (IOException caught) { ... } catch (OutOfMemoryException) { ... } catch { ... throw ; } name is optional general catch block
    • 78. finally <ul><li>you can ensure code always runs </li></ul><ul><ul><li>in a finally { block } </li></ul></ul><ul><ul><li>exception in finally block dominates </li></ul></ul><ul><ul><li>you cannot jump out of a finally block </li></ul></ul>TextReader reader = null ; try { FileInfo source = new FileInfo(filename); int length = ( int )source.Length; char [] contents = new char [length]; reader = source.OpenText(); reader.Read(contents, 0, length); ... } ... finally { if (reader != null ) { reader.Close(); } } definite assignment rules, OK
    • 79. Local Resources <ul><li>deterministic finalisation via finally ... </li></ul><ul><ul><li>is exception safe, but... </li></ul></ul><ul><ul><li>is repetitive and doesn't scale </li></ul></ul><ul><ul><li>is complex and fails to abstract </li></ul></ul>TextReader reader = null ; try { FileInfo source = new FileInfo(filename); int length = ( int )source.Length; char [] contents = new char [length]; reader = source.OpenText(); reader.Read(contents, 0, length); ... } ... finally { if (reader != null ) { reader.Close(); } }
    • 80. using Statements <ul><li>after discussions on the .NET reflector </li></ul><ul><ul><li>M'Soft provided a solution consisting of... </li></ul></ul><ul><ul><li>the IDisposable interface in combination with... </li></ul></ul><ul><ul><li>the using statement </li></ul></ul>using ( type variable = init) embedded - statement { type variable = init ; try { embedded - statement } finally { if ( variable != null ) { ((IDisposable) variable ).Dispose(); } } } precisely equivalent to
    • 81. IDisposable struct AutoClosing : IDisposable { public AutoClosing(TextReader reader) { if (reader == null ) { throw new ArgumentNullException(); } target = reader; } public void Dispose() { target.Close(); } private readonly TextReader target; } interface IDisposable { void Dispose(); }
    • 82. Preference? ... TextReader reader = source.OpenText(); using ( new AutoClosing(reader)) { reader.Read(contents, 0, length); ... } TextReader reader = null ; try { ... reader = source.OpenText(); reader.Read(contents, 0, length); ... } finally { if (reader != null ) { reader.Close(); } } Before... ...After
    • 83. lock <ul><li>C# does not have a synchronize keyword </li></ul><ul><ul><li>it has lock statements </li></ul></ul>public class Monitor { public static void Enter( object ); public static void Exit( object ); ... } lock ( expression ) e mbedded - statement System.Threading.Monitor.Enter( expression ); try { embedded - statement } finally { System.Threading.Monitor.Exit( expression ) ; } precisely equivalent to ( expression is evaluated once)
    • 84. Exception Notes <ul><li>throw specifications - NO </li></ul><ul><li>checked/unchecked distinction - NO </li></ul><ul><li>compile time exceptions - NO </li></ul>
    • 85. Garbage Collection C# Programming Fundamentals Objects Relationships Systems
    • 86. The Miracle of Birth <ul><li>object birth is a two phase process </li></ul><ul><ul><li>allocate the raw memory </li></ul></ul><ul><ul><ul><li>using operator new </li></ul></ul></ul><ul><ul><ul><li>{ 1,2,3,4 } is an [ ]array shorthand </li></ul></ul></ul><ul><ul><ul><li>&quot;literal&quot; is a string shorthand </li></ul></ul></ul><ul><ul><li>initialise an object in the memory </li></ul></ul><ul><ul><ul><li>using a constructor </li></ul></ul></ul><ul><ul><ul><li>you can't use a constructor without new </li></ul></ul></ul>Get that would you, Deidre....
    • 87. Death <ul><li>object death is a two phase process </li></ul><ul><ul><li>finalise the object back to raw memory </li></ul></ul><ul><ul><li>deallocate the raw memory back to the heap </li></ul></ul><ul><li>C++ – deterministic </li></ul><ul><ul><li>user calls destructor </li></ul></ul><ul><ul><li>user calls operator delete </li></ul></ul><ul><li>C# – non deterministic (like Java) </li></ul><ul><ul><li>GC calls Finalize </li></ul></ul><ul><ul><li>GC reclaims heap memory </li></ul></ul>Shall we take our cars?
    • 88. Finalize <ul><li>garbage collector finalizes objects </li></ul><ul><ul><li>when they become unreachable </li></ul></ul><ul><ul><li>by calling Finalize( ) </li></ul></ul><ul><ul><li>but you cannot override Object.Finalize!! </li></ul></ul><ul><ul><li>or call it </li></ul></ul>public class Resource { ... public void Dispose() { this .Finalize(); } protected override void Finalize() { ... } } compile time errors
    • 89. Destructor <ul><li>instead you write a destructor </li></ul><ul><ul><li>which the compiler translates into Finalize </li></ul></ul><ul><ul><li>can be declared in a class but not a struct </li></ul></ul><ul><ul><li>automatically calls its base class Finalize </li></ul></ul><ul><ul><li>can only be called by garbage collector </li></ul></ul>public class Resource { ... ~Resource() { //... } ... } public class Resource { ... protected override void Finalize() { //... base .Finalize(); } ... }
    • 90. GC Notes <ul><li>Beta-2 </li></ul><ul><ul><li>destructors are called when program exits :-) </li></ul></ul><ul><ul><li>API to toggle this behavior :-) </li></ul></ul><ul><ul><li>Finalize can make this known again </li></ul></ul><ul><ul><ul><li>complex resurrection issues, slows GC :-( </li></ul></ul></ul><ul><ul><li>what happens if Finalize throws ? </li></ul></ul><ul><ul><ul><li>specification doesn't say :-( </li></ul></ul></ul>
    • 91. Nested Types C# Programming Fundamentals Objects Relationships Systems
    • 92. Nested Types <ul><li>a class or struct can declare nested types </li></ul><ul><ul><li>nested types default to private access </li></ul></ul><ul><ul><li>non-nested types default to internal access </li></ul></ul>class Outer { interface Space { } abstract class Reaches { } class Limits { } sealed class Hebrides { } struct Mongolia { } } internal access private access
    • 93. Nested Access <ul><li>a nested type... </li></ul><ul><ul><li>has access to all members of outer types </li></ul></ul><ul><ul><li>but not vice versa </li></ul></ul><ul><ul><li>C# follows Java access model </li></ul></ul>class Outer { public class Inner { private void peek(Outer can) { can.peek( this ); } } private void peek(Inner cannot) { cannot.peek( this ); } } OK Fails Outer.peek(Inner cannot) Inner.peek(Outer can)
    • 94. Access Modifiers <ul><li>there are five kinds of access </li></ul><ul><ul><li>nested types can have any access modifier </li></ul></ul><ul><ul><li>non-nested types can be public or internal </li></ul></ul>internal protected internal private protected Y public Y non-nested Y Y Y Y nested Y protected OR internal
    • 95. Semantics <ul><li>C# nested types are implicitly static </li></ul><ul><ul><li>C# does not have Java inner classes </li></ul></ul><ul><ul><li>C# does not have Java local classes </li></ul></ul><ul><ul><li>C# does not have Java anonymous classes </li></ul></ul>class Outer { ... class Nested { ... } ... } Outer.Nested « class » Outer « class » Outer$Inner « class » Outer « class » Outer.this 1 C#, C++ Java
    • 96. Delegates C# Programming Fundamentals Objects Relationships Systems
    • 97. delegate Type <ul><li>a delegate is the last C# type... </li></ul><ul><ul><li>declares a named signature including return type </li></ul></ul><ul><ul><li>like a C++ function pointer/object </li></ul></ul><ul><ul><li>similar to a Delphi closure </li></ul></ul>delegate void Func( string s); class Eg { public static void ForAll( string [] args, Func call) { foreach ( string arg in args) { call(arg); } } } Func is a type name
    • 98. static Method <ul><li>a delegate instance... </li></ul><ul><ul><li>can hold and call a static method </li></ul></ul>delegate void Func( string s); ... class Test { static void Display( string s) { ... } static void Main( string [] args) { Eg.ForAll(args, new Func(Test.Display)); Eg.ForAll(args, new Func(Display)); } } note no ( ) create a delegate instance
    • 99. Instance Method <ul><li>a delegate instance... </li></ul><ul><ul><li>can hold and call an instance method </li></ul></ul>delegate void Func( string s); ... class Test { void Stash( string s) { ... } void NotMain( string [] args) { Eg.ForAll(args, new Func( this .Stash)); Eg.ForAll(args, new Func(Stash)); } }
    • 100. Remember This? delegate void Method(); ... TextReader reader = source.OpenText(); using ( new Finally( new Method(reader.Close))) { reader.Read(contents, 0, length); ... } TextReader reader = null ; try { ... reader = source.OpenText(); reader.Read(contents, 0, length); ... } finally { if (reader != null ) { reader.Close(); } } ...After Before...
    • 101. Finally public delegate void Method(); public struct Finally : IDisposable { public Finally(Method call) { if (call == null ) { throw new ArgumentNullException(); } this .call = call; } public override void Dispose() { call(); } private readonly Method call; }
    • 102. Mulitcast delegate <ul><li>a void return type delegate ... </li></ul><ul><ul><li>can hold multiple callback in its invocation list </li></ul></ul><ul><ul><li>first in, first called </li></ul></ul>delegate void Pred( string s); ... class Test { void DoThis( string s) { ... } static void ThenThat( string s) { ... } void Method( string arg) { Pred call = null ; call += new Pred( this .DoThis); call += new Pred(Test.ThenThat); ... call(arg); } }
    • 103. delegate Notes <ul><li>delegates </li></ul><ul><ul><li>are called directly from invokers thread </li></ul></ul><ul><ul><li>can be compared for equality </li></ul></ul><ul><ul><li>can be ref and out parameters </li></ul></ul><ul><ul><li>are implicitly sealed types </li></ul></ul><ul><li>combinable delegate </li></ul><ul><ul><li>void return type </li></ul></ul><ul><ul><li>implicitly derive from System.Delegate </li></ul></ul><ul><li>non-combinable delegate </li></ul><ul><ul><li>non void return type </li></ul></ul><ul><ul><li>no out parameters </li></ul></ul><ul><ul><li>implicitly derive from System.MultiCastDelegate </li></ul></ul>
    • 104. Events C# Programming Fundamentals Objects Relationships Systems
    • 105. event Delegates <ul><li>a delegate field can be marked as an event </li></ul><ul><ul><li>only += and -= can be performed on the field </li></ul></ul><ul><ul><li>used widely in GUI classes </li></ul></ul>namespace System.Windows.Forms { public class Button : ... { ... public event EventHandler Click; ... ... protected void OnClick(EventArgs e) { if (Click != null ) { Click( this , e); } } ... } }
    • 106. Event Delegates <ul><li>.NET framework has many event delegates </li></ul><ul><ul><li>by convention first parameter is event sender </li></ul></ul><ul><ul><li>and second parameter derives from EventArgs </li></ul></ul>namespace System { public delegate void EventHandler ( object sender, EventArgs e ); ... public class EventArgs { ... } }
    • 107. Event Example <ul><li>easy to imagine this in Java... </li></ul><ul><ul><li>using an anonymous class </li></ul></ul>using System; using System.Windows.Forms; class MyForm : Form { private void InitializeComponent() { openFile = new Button(); ... openFile.Click += new EventHandler(OpenFile); } protected void OpenFile( object sender, EventArgs e) { ... } private Button openFile; } Note case difference: openFile vs OpenFile
    • 108. Event Properties <ul><li>event fields can be exposed as properties </li></ul><ul><ul><li>consider a class with lots of event s </li></ul></ul><ul><ul><li>lazy creation might be useful </li></ul></ul><ul><ul><li>+= forwards to add </li></ul></ul><ul><ul><li>-= forwards to remove </li></ul></ul>namespace System.Windows.Forms { public class Button : ... { ... public event EventHandler Click { add { ... } remove { ... } } ... } }
    • 109. Namespaces C# Programming Fundamentals Objects Relationships Systems
    • 110. namespace <ul><li>a namespace is a logical naming mechanism </li></ul><ul><ul><li>no relation to directory names or assemblies </li></ul></ul><ul><ul><li>a single .cs file can declare several namespaces </li></ul></ul><ul><ul><li>implicitly public </li></ul></ul><ul><ul><li>handy shorthand </li></ul></ul><ul><ul><li>no anonymous namespace </li></ul></ul>namespace Accu { namespace Conference { ... } } namespace Informant { ... } namespace Accu.Conference { ... ... ... ... } namespace Informant { ... }
    • 111. using Directive <ul><li>only allowed at the start of namespace </li></ul><ul><ul><li>respect scope, not recursive, no clash if no use </li></ul></ul><ul><ul><li>never affect other using directives </li></ul></ul>using System; class Bar { ... } namespace Accu.Conference { using System.Collections; ... class Foo : Bar { static void Main(String[] args) { Console.Write(args[0]); } ... private Hashtable store; } }
    • 112. using Alias <ul><li>a using alias creates alias for... </li></ul><ul><ul><li>a namespace, or </li></ul></ul><ul><ul><li>a type </li></ul></ul>namespace CSharp { using Vector = System.Collections.ArrayList; class SourceFile { ... Vector tokens; } }
    • 113. Namespace Notes <ul><li>using </li></ul><ul><ul><li>only at start of namespace </li></ul></ul><ul><ul><li>respects scope </li></ul></ul><ul><ul><li>never affect subsequent using directives </li></ul></ul><ul><ul><li>never affect subsequent using aliases </li></ul></ul><ul><li>namespace </li></ul><ul><ul><li>top level, non nested classes </li></ul></ul><ul><ul><li>public or internal , default to internal </li></ul></ul><ul><ul><li>cannot be protected or private </li></ul></ul>
    • 114. Assemblies C# Programming Fundamentals Objects Relationships Systems
    • 115. Modules <ul><li>a physical .NET .DLL </li></ul><ul><ul><li>contains types and MSIL code </li></ul></ul><ul><ul><li>unit of dynamic download </li></ul></ul><ul><li>a PE (portable executable) file written using </li></ul><ul><ul><li>C#, VB.NET, managed C++, raw MSIL, others... </li></ul></ul><ul><ul><li>but not a mixture </li></ul></ul>C:> csc ... /target:module ...
    • 116. Assembly <ul><li>a logical .NET .DLL containing... </li></ul><ul><ul><li>manifest containing metadata </li></ul></ul><ul><ul><ul><li>name, version#, file-list </li></ul></ul></ul><ul><ul><ul><li>referenced assemblies </li></ul></ul></ul><ul><ul><ul><li>type-list  containing module </li></ul></ul></ul><ul><ul><ul><li>security permissions </li></ul></ul></ul><ul><ul><li>one or more modules containing types </li></ul></ul><ul><ul><ul><li>one containing assembly entry point </li></ul></ul></ul><ul><ul><li>zero or more resources </li></ul></ul><ul><ul><ul><li>bitmaps, icons, etc </li></ul></ul></ul>physically or logically containing C:> csc ... /target:library ... C:> csc ... /addmodule:... C:> csc ... /target:exe /reference:...
    • 117. Deployment <ul><li>to deploy an assembly... </li></ul><ul><ul><li>drop it and its linked files into a single directory </li></ul></ul><ul><ul><li>goodbye registry </li></ul></ul><ul><li>private assemblies... </li></ul><ul><ul><li>live in their application's directory </li></ul></ul><ul><ul><li>are not versioned </li></ul></ul><ul><li>shared assemblies... </li></ul><ul><ul><li>live in a shared directory (Global Assembly Cache) </li></ul></ul><ul><ul><li>are versioned </li></ul></ul><ul><ul><li>need a shared name (aka strong name) </li></ul></ul><ul><ul><ul><li>textual name </li></ul></ul></ul><ul><ul><ul><li>public key </li></ul></ul></ul><ul><ul><ul><li>digital signature </li></ul></ul></ul>
    • 118. Versioning <ul><li>assemblies with different versions co-exist </li></ul><ul><ul><li>allows assembly evolution management </li></ul></ul><ul><ul><li>never modify an existing assembly </li></ul></ul><ul><ul><li>instead, create a new assembly with a new version </li></ul></ul><major>.<minor>.<build>.<revision> incompatible maybe compatible Quick Fix Engineering
    • 119. Version Policy <ul><li>update policy controlled via .XML text file </li></ul><ul><ul><li>default </li></ul></ul><ul><ul><ul><li>major.minor as built </li></ul></ul></ul><ul><ul><li>specific </li></ul></ul><ul><ul><ul><li>major.minor as specified </li></ul></ul></ul><ul><ul><li>QFE </li></ul></ul><ul><ul><ul><li>latest build.revision? </li></ul></ul></ul><ul><ul><li>safe </li></ul></ul><ul><ul><ul><li>exactly as built </li></ul></ul></ul>... <BindingPolicy> <BindingRedir Name=&quot;Wibble&quot; Originator=&quot;32ab4ba45e0a69a1&quot; Version=&quot;*&quot; VersionNew=&quot;6.1.1212.14&quot; UseLatestBuildRevision=&quot;no&quot;/> </BindingPolicy>
    • 120. internal access <ul><li>logical access control </li></ul><ul><ul><li>public, protected, private </li></ul></ul><ul><li>physical access control </li></ul><ul><ul><li>internal access is within assembly </li></ul></ul>an assembly of four classes public internal private
    • 121. [Attributes] C# Programming Fundamentals Objects Relationships Systems
    • 122. What Are They? <ul><li>attributes allow code elements to... </li></ul><ul><ul><li>be tagged with declarative information </li></ul></ul><ul><ul><li>which is then added to the metadata </li></ul></ul><ul><ul><li>which can queried using reflection </li></ul></ul><ul><li>for example... </li></ul><ul><ul><li>suppose you wanted to record which developers implemented which types </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>create a class to represent the developer info </li></ul></ul><ul><ul><li>tag types with the developer attribute </li></ul></ul><ul><ul><li>specify developer attribute is only for types </li></ul></ul><ul><ul><li>decide whether to allow multiple tags </li></ul></ul>
    • 123. Attribute Class <ul><li>create attribute class </li></ul><ul><ul><li>must derive from System.Attribute </li></ul></ul><ul><ul><li>recommedation – use Attribute suffix in name </li></ul></ul>... public sealed class DeveloperAttribute : System.Attribute { ... public DeveloperAttribute( string name) { ... } ... }
    • 124. [ tag ] <ul><li>tag code elements with [attribute]'s </li></ul><ul><ul><li>ConstInt struct is tagged [ DeveloperAttribute ] </li></ul></ul>[DeveloperAttribute(&quot;Jon Jagger&quot;)] public struct ConstInt { public ConstInt( int value) { this .value = value; } public static implicit operator int (ConstInt from) { return from.value; } private readonly int value; }
    • 125. Problem <ul><li>how can you specify which kind of code elements the attribute is to be used with? </li></ul><ul><ul><li>Assembly, Module </li></ul></ul><ul><ul><li>Interface, Class, Struct, Enum, Delegate </li></ul></ul><ul><ul><li>Constructor, Method, Property, Field, Event </li></ul></ul><ul><ul><li>Parameter, ReturnValue </li></ul></ul><ul><ul><li>All </li></ul></ul>
    • 126. AttributeUsage <ul><li>use a predefined AttributeUsage attribute! </li></ul><ul><ul><li>with AttributeTarget enum </li></ul></ul>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class DeveloperAttribute : System.Attribute { ... public DeveloperAttribute( string name) { ... } ... }
    • 127. Multiple Tags <ul><li>decide whether to allow multiple tags </li></ul><ul><ul><li>use named parameter, AllowMultiple = true </li></ul></ul>[AttributeUsage(AttributeTargets.Class | ..., AllowMultiple = true )] public sealed class DeveloperAttribute : System.Attribute { ... public DeveloperAttribute( string name) { ... } ... } [DeveloperAttribute(&quot;Jon Jagger&quot;)] [DeveloperAttribute(&quot;Patrick Jagger&quot;)] public struct ConstInt { ... }
    • 128. Positional <ul><li>positional parameters </li></ul><ul><ul><li>must be specified in the attribution </li></ul></ul><ul><ul><li>correspond to constructor arguments </li></ul></ul>... public sealed class DeveloperAttribute : System.Attribute { public DeveloperAttribute( string name) { ... } ... } [DeveloperAttribute(&quot;Jon Jagger&quot;)] public struct ConstInt { ... }
    • 129. Named <ul><li>named parameters </li></ul><ul><ul><li>optionally specified in the attribution </li></ul></ul><ul><ul><li>must correspond to fields/properties </li></ul></ul><ul><ul><ul><li>(non- static , public , read-write) </li></ul></ul></ul>... public sealed class DeveloperAttribute : System.Attribute { public DeveloperAttribute( string name) ... ... public string TelExt { get {...} set {...} } } [DeveloperAttribute(&quot;Patrick Jagger&quot;)] [DeveloperAttribute(&quot;Jon Jagger&quot;, TelExt=&quot;4263&quot;)] public struct ConstInt { ... }
    • 130. metadata <ul><li>attributes are added to assembly metadata </li></ul><ul><ul><li>visible though ILDASM or reflection </li></ul></ul>
    • 131. Notes <ul><li>attributes are checked at compile time </li></ul><ul><ul><li>incorrect usage causes compile time error </li></ul></ul><ul><li>predefined attribute classes include </li></ul><ul><ul><li>[Conditional] </li></ul></ul><ul><ul><li>[Obsolete] </li></ul></ul><ul><ul><li>[CLSCompliant] </li></ul></ul><ul><ul><li>[Serializable] </li></ul></ul><ul><li>attribute parameter types limited to </li></ul><ul><ul><li>bool, byte, char, double, float, int, long, short </li></ul></ul><ul><ul><li>string, object </li></ul></ul><ul><ul><li>public enums </li></ul></ul><ul><ul><li>Type </li></ul></ul><ul><li>CLS attribute based templates </li></ul><ul><ul><li>check out www.newtelligence.com </li></ul></ul>
    • 132. Reflection C# Programming Fundamentals Objects Relationships Systems
    • 133. Terminology <ul><li>.NET has almost perfect reflection </li></ul><ul><ul><li>reflection API's even allow dynamic creation </li></ul></ul>Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. There are two apects to such manipulation: Introspection is the ability of a program to observe and therefore reason about its own state. Intercession is the ability of a program to modify its own execution state or alter its own interpretation or meaning. Both apects require a mechanism for encoding execution state as data; providing such an encoding is called reification Richard Gabriel, et al
    • 134. Attributes <ul><li>retrieving custom attributes </li></ul>public sealed class DeveloperAttribute ... { ... public override string ToString() { ... } ... } public class Example { static void Main() { string typename = &quot;ConstInt&quot;; Type t = Type.GetType(typename); object [] atts = t.GetCustomAttributes( true ); foreach ( object att in atts) { Console.WriteLine(att); } } }
    • 135. Remember This? TextReader reader = source.OpenText(); using ( new Finally(reader, &quot;Close&quot; )) { reader.Read(contents, 0, length); ... } TextReader reader = null ; try { ... reader = source.OpenText(); reader.Read(contents, 0, length); ... } finally { if (reader != null ) { reader.Close(); } } ...After
    • 136. Finally using System; using System.Reflection; public struct Finally : IDisposable { public Finally( object target, string methodName) { this .target = target; this .methodName = methodName; } public void Dispose() { Type t = target.GetType(); MethodInfo method = t.GetMethod(methodName); if (method != null ) { t.InvokeMember( methodName, BindingFlags.InvokeMethod, target, new object [0] ); } } private readonly object target; private readonly string methodName; }
    • 137. Summary <ul><li>arrays: rectangular, ragged, params </li></ul><ul><li>string: immutable, readonly[], verbatim </li></ul><ul><li>class: ref/out, static c'tor, boxing </li></ul><ul><li>exceptions: lock, no throw-specs </li></ul><ul><li>GC: d'tor, using statement, IDisposable </li></ul><ul><li>inheritance: positional, virtual/override </li></ul><ul><li>interfaces: no fields, EII, properties, indexers </li></ul><ul><li>nested types: Java access, C++ semantics </li></ul><ul><li>delegates: function pointers, single and multicast </li></ul><ul><li>events: restricted multicast delegate </li></ul><ul><li>assemblies: logical DLL, no registry, versioning </li></ul><ul><li>namespaces: shorthand syntax </li></ul><ul><li>reflection: metadata, introspection, intercession </li></ul><ul><li>attributes: add to metadata, reflect </li></ul>
    • 138. Standards <ul><li>ECMA/TC39/2000-2 </li></ul><ul><ul><li>Standard 1, C# </li></ul></ul><ul><ul><li>Standard 2, Common Language Infrastructure </li></ul></ul><ul><li>Timeline </li></ul><ul><ul><li>March 2001 – draft submission </li></ul></ul><ul><ul><li>Sept 2001 – final submission </li></ul></ul><ul><ul><li>Dec 2001 – Version 1 adopted by GA </li></ul></ul><ul><ul><li>Jan 2002 – submit to ISO for fast track process </li></ul></ul>
    • 139. Bibliography <ul><li>Presenting C# </li></ul><ul><ul><li>Christophe Wille; SAMS </li></ul></ul><ul><li>A Programmer's Introduction to C# </li></ul><ul><ul><li>Eric Gunnerson; Apress </li></ul></ul><ul><li>Programming C# with the public Beta </li></ul><ul><ul><li>Harvey, Robinson,Templeman, Watson; Wrox </li></ul></ul><ul><li>C# Essentials </li></ul><ul><ul><li>Albahari, Drayton, Merrill; O'Reilly </li></ul></ul><ul><li>Inside C# </li></ul><ul><ul><li>Tom Archer; MS Press </li></ul></ul>

    ×