diff --git a/10_delegates/anonymous_1.cs b/10_delegates/anonymous_1.cs new file mode 100644 index 0000000..5cef195 --- /dev/null +++ b/10_delegates/anonymous_1.cs @@ -0,0 +1,56 @@ +using System; + +public delegate int ProcStrategy( int x ); + +public class Processor +{ + private ProcStrategy strategy; + public ProcStrategy Strategy { + set { + strategy = value; + } + } + + public int[] Process( int[] array ) { + int[] result = new int[ array.Length ]; + for( int i = 0; i < array.Length; ++i ) { + result[i] = strategy( array[i] ); + } + return result; + } +} + +public class EntryPoint +{ + private static int MultiplyBy2( int x ) { + return x*2; + } + + private static int MultiplyBy4( int x ) { + return x*4; + } + + private static void PrintArray( int[] array ) { + for( int i = 0; i < array.Length; ++i ) { + Console.Write( "{0}", array[i] ); + if( i != array.Length-1 ) { + Console.Write( ", " ); + } + } + Console.Write( "\n" ); + } + + static void Main() { + // Create an array of integers. + int[] integers = new int[] { + 1, 2, 3, 4 + }; + + Processor proc = new Processor(); + proc.Strategy = new ProcStrategy( EntryPoint.MultiplyBy2 ); + PrintArray( proc.Process(integers) ); + + proc.Strategy = new ProcStrategy( EntryPoint.MultiplyBy4 ); + PrintArray( proc.Process(integers) ); + } +} diff --git a/10_delegates/anonymous_2.cs b/10_delegates/anonymous_2.cs new file mode 100644 index 0000000..5cf3311 --- /dev/null +++ b/10_delegates/anonymous_2.cs @@ -0,0 +1,57 @@ +using System; + +public delegate int ProcStrategy( int x ); + +public class Processor +{ + private ProcStrategy strategy; + public ProcStrategy Strategy { + set { + strategy = value; + } + } + + public int[] Process( int[] array ) { + int[] result = new int[ array.Length ]; + for( int i = 0; i < array.Length; ++i ) { + result[i] = strategy( array[i] ); + } + return result; + } +} + +public class EntryPoint +{ + private static void PrintArray( int[] array ) { + for( int i = 0; i < array.Length; ++i ) { + Console.Write( "{0}", array[i] ); + if( i != array.Length-1 ) { + Console.Write( ", " ); + } + } + Console.Write( "\n" ); + } + + static void Main() { + // Create an array of integers. + int[] integers = new int[] { + 1, 2, 3, 4 + }; + + Processor proc = new Processor(); + proc.Strategy = delegate(int x) { + return x*2; + }; + PrintArray( proc.Process(integers) ); + + proc.Strategy = delegate(int x) { + return x*4; + }; + PrintArray( proc.Process(integers) ); + + proc.Strategy = delegate { + return 0; + }; + PrintArray( proc.Process(integers) ); + } +} diff --git a/10_delegates/anonymous_3.cs b/10_delegates/anonymous_3.cs new file mode 100644 index 0000000..f5329dd --- /dev/null +++ b/10_delegates/anonymous_3.cs @@ -0,0 +1,75 @@ +using System; + +public delegate int ProcStrategy( int x ); + +public class Processor +{ + private ProcStrategy strategy; + public ProcStrategy Strategy { + set { strategy = value; } + } + + public int[] Process( int[] array ) { + int[] result = new int[ array.Length ]; + for( int i = 0; i < array.Length; ++i ) { + result[i] = strategy( array[i] ); + } + return result; + } +} + +public class Factor +{ + public Factor( int fact ) { + this.fact = fact; + } + + private int fact; + + public ProcStrategy Multiplier { + get { + // This is an anonymous method. + return delegate(int x) { + return x*fact; + }; + } + } + + public ProcStrategy Adder { + get { + // This is an anonymous method. + return delegate(int x) { + return x+fact; + }; + } + } +} + +public class EntryPoint +{ + private static void PrintArray( int[] array ) { + for( int i = 0; i < array.Length; ++i ) { + Console.Write( "{0}", array[i] ); + if( i != array.Length-1 ) { + Console.Write( ", " ); + } + } + Console.Write( "\n" ); + } + + static void Main() { + // Create an array of integers. + int[] integers = new int[] { + 1, 2, 3, 4 + }; + + Factor factor = new Factor( 2 ); + Processor proc = new Processor(); + proc.Strategy = factor.Multiplier; + PrintArray( proc.Process(integers) ); + + proc.Strategy = factor.Adder; + factor = null; + PrintArray( proc.Process(integers) ); + } +} diff --git a/10_delegates/basic_use_1.cs b/10_delegates/basic_use_1.cs new file mode 100644 index 0000000..6f62cc4 --- /dev/null +++ b/10_delegates/basic_use_1.cs @@ -0,0 +1,44 @@ +using System; + +public delegate double ProcessResults( double x, + double y ); + +public class Processor +{ + public Processor( double factor ) { + this.factor = factor; + } + + public double Compute( double x, double y ) { + double result = (x+y)*factor; + Console.WriteLine( "InstanceResults: {0}", result ); + return result; + } + + public static double StaticCompute( double x, + double y ) { + double result = (x+y)*0.5; + Console.WriteLine( "StaticResult: {0}", result ); + return result; + } + + private double factor; +} + +public class EntryPoint +{ + static void Main() { + Processor proc1 = new Processor( 0.75 ); + Processor proc2 = new Processor( 0.83 ); + + ProcessResults delegate1 = new ProcessResults( proc1.Compute ); + ProcessResults delegate2 = new ProcessResults( proc2.Compute ); + ProcessResults delegate3 = new ProcessResults( Processor.StaticCompute ); + + double combined = delegate1( 4, 5 ) + + delegate2( 6, 2 ) + + delegate3( 5, 2 ); + + Console.WriteLine( "Output: {0}", combined ); + } +} diff --git a/10_delegates/binder_1.cs b/10_delegates/binder_1.cs new file mode 100644 index 0000000..73c1a3a --- /dev/null +++ b/10_delegates/binder_1.cs @@ -0,0 +1,39 @@ +using System; + +public delegate int Operation( int x, int y ); + +public class Bind2nd +{ + public delegate int BoundDelegate( int x ); + + public Bind2nd( Operation del, int arg2 ) { + this.del = del; + this.arg2 = arg2; + } + + public BoundDelegate Binder { + get { + return delegate( int arg1 ) { + return del( arg1, arg2 ); + }; + } + } + + private Operation del; + private int arg2; +} + +public class EntryPoint +{ + static int Add( int x, int y ) { + return x + y; + } + + static void Main() { + Bind2nd binder = new Bind2nd( + new Operation(EntryPoint.Add), + 4 ); + + Console.WriteLine( binder.Binder(2) ); + } +} diff --git a/10_delegates/binder_2.cs b/10_delegates/binder_2.cs new file mode 100644 index 0000000..2247ed5 --- /dev/null +++ b/10_delegates/binder_2.cs @@ -0,0 +1,40 @@ +using System; + +public delegate int Operation( int x, int y ); + +// WILL NOT COMPILE !!! +public class Bind2nd< DelegateType > +{ + public delegate int BoundDelegate( int x ); + + public Bind2nd( DelegateType del, int arg2 ) { + this.del = del; + this.arg2 = arg2; + } + + public BoundDelegate Binder { + get { + return delegate( int arg1 ) { + return del( arg1, arg2 ); // OUCH! + }; + } + } + + private DelegateType del; + private int arg2; +} + +public class EntryPoint +{ + static int Add( int x, int y ) { + return x + y; + } + + static void Main() { + Bind2nd binder = new Bind2nd( + new Operation(EntryPoint.Add), + 4 ); + + Console.WriteLine( binder.Binder(2) ); + } +} diff --git a/10_delegates/binder_3.cs b/10_delegates/binder_3.cs new file mode 100644 index 0000000..98625ff --- /dev/null +++ b/10_delegates/binder_3.cs @@ -0,0 +1,41 @@ +using System; + +public delegate int Operation( int x, int y ); + +// STILL WILL NOT COMPILE !!! +public class Bind2nd< DelegateType > + where DelegateType : Delegate +{ + public delegate int BoundDelegate( int x ); + + public Bind2nd( DelegateType del, int arg2 ) { + this.del = del; + this.arg2 = arg2; + } + + public BoundDelegate Binder { + get { + return delegate( int arg1 ) { + return del( arg1, arg2 ); // OUCH! + }; + } + } + + private DelegateType del; + private int arg2; +} + +public class EntryPoint +{ + static int Add( int x, int y ) { + return x + y; + } + + static void Main() { + Bind2nd binder = new Bind2nd( + new Operation(EntryPoint.Add), + 4 ); + + Console.WriteLine( binder.Binder(2) ); + } +} diff --git a/10_delegates/binder_4.cs b/10_delegates/binder_4.cs new file mode 100644 index 0000000..b362e22 --- /dev/null +++ b/10_delegates/binder_4.cs @@ -0,0 +1,59 @@ +using System; +using System.Reflection; + +public delegate int Operation( int x, int y ); + +public class Bind2nd +{ + public delegate ReturnType UnboundDelegate( UBArg1Type arg1, UBArg2Type arg2 ); + public delegate ReturnType BoundDelegate( BArg1Type x ); + + public Bind2nd( Delegate del, Arg2Type arg2 ) { + // Get the types from the delegate. + object target = del.Target; + MethodInfo targetMethod = del.Method; + Type targetType = targetMethod.ReflectedType; + + if( target == null ) { + // Static method + this.del = (UnboundDelegate) Delegate.CreateDelegate( + typeof(UnboundDelegate), + targetType, + targetMethod.Name ); + + } else { + // Instance method + this.del = (UnboundDelegate) Delegate.CreateDelegate( + typeof(UnboundDelegate), + target, + targetMethod.Name ); + } + this.arg2 = arg2; + } + + public BoundDelegate Binder { + get { + return delegate( Arg1Type arg1 ) { + return del( arg1, arg2 ); + }; + } + } + + private UnboundDelegate del; + private Arg2Type arg2; +} + +public class EntryPoint +{ + static int Add( int x, int y ) { + return x + y; + } + + static void Main() { + Bind2nd binder = new Bind2nd( + new Operation(EntryPoint.Add), + 4 ); + + Console.WriteLine( binder.Binder(2) ); + } +} diff --git a/10_delegates/capture_1.cs b/10_delegates/capture_1.cs new file mode 100644 index 0000000..c30252d --- /dev/null +++ b/10_delegates/capture_1.cs @@ -0,0 +1,25 @@ +using System; + +public delegate void PrintAndIncrement(); + +public class EntryPoint +{ + public static PrintAndIncrement[] CreateDelegates() { + PrintAndIncrement[] delegates = new PrintAndIncrement[3]; + int someVariable = 0; + int anotherVariable = 1; + for( int i = 0; i < 3; ++i ) { + delegates[i] = delegate { + Console.WriteLine( someVariable++ ); + }; + } + return delegates; + } + + static void Main() { + PrintAndIncrement[] delegates = CreateDelegates(); + for( int i = 0; i < 3; ++i ) { + delegates[i](); + } + } +} diff --git a/10_delegates/capture_2.cs b/10_delegates/capture_2.cs new file mode 100644 index 0000000..0691650 --- /dev/null +++ b/10_delegates/capture_2.cs @@ -0,0 +1,24 @@ +using System; + +public delegate void PrintAndIncrement(); + +public class EntryPoint +{ + public static PrintAndIncrement[] CreateDelegates() { + PrintAndIncrement[] delegates = new PrintAndIncrement[3]; + for( int i = 0; i < 3; ++i ) { + int someVariable = 0; + delegates[i] = delegate { + Console.WriteLine( someVariable++ ); + }; + } + return delegates; + } + + static void Main() { + PrintAndIncrement[] delegates = CreateDelegates(); + for( int i = 0; i < 3; ++i ) { + delegates[i](); + } + } +} diff --git a/10_delegates/chained_1.cs b/10_delegates/chained_1.cs new file mode 100644 index 0000000..788e1b0 --- /dev/null +++ b/10_delegates/chained_1.cs @@ -0,0 +1,46 @@ +using System; + +public delegate double ProcessResults( double x, + double y ); + +public class Processor +{ + public Processor( double factor ) { + this.factor = factor; + } + + public double Compute( double x, double y ) { + double result = (x+y)*factor; + Console.WriteLine( "InstanceResults: {0}", result ); + return result; + } + + public static double StaticCompute( double x, + double y ) { + double result = (x+y)*0.5; + Console.WriteLine( "StaticResult: {0}", result ); + return result; + } + + private double factor; +} + +public class EntryPoint +{ + static void Main() { + Processor proc1 = new Processor( 0.75 ); + Processor proc2 = new Processor( 0.83 ); + + ProcessResults[] delegates = new ProcessResults[] { + new ProcessResults( proc1.Compute ), + new ProcessResults( proc2.Compute ), + new ProcessResults( Processor.StaticCompute ) + }; + + ProcessResults chained = (ProcessResults) Delegate.Combine( delegates ); + + double combined = chained( 4, 5 ); + + Console.WriteLine( "Output: {0}", combined ); + } +} diff --git a/10_delegates/chained_2.cs b/10_delegates/chained_2.cs new file mode 100644 index 0000000..4cb900b --- /dev/null +++ b/10_delegates/chained_2.cs @@ -0,0 +1,50 @@ +using System; + +public delegate double ProcessResults( double x, + double y ); + +public class Processor +{ + public Processor( double factor ) { + this.factor = factor; + } + + public double Compute( double x, double y ) { + double result = (x+y)*factor; + Console.WriteLine( "InstanceResults: {0}", result ); + return result; + } + + public static double StaticCompute( double x, + double y ) { + double result = (x+y)*0.5; + Console.WriteLine( "StaticResult: {0}", result ); + return result; + } + + private double factor; +} + +public class EntryPoint +{ + static void Main() { + Processor proc1 = new Processor( 0.75 ); + Processor proc2 = new Processor( 0.83 ); + + ProcessResults[] delegates = new ProcessResults[] { + new ProcessResults( proc1.Compute ), + new ProcessResults( proc2.Compute ), + new ProcessResults( Processor.StaticCompute ) + }; + + ProcessResults chained = (ProcessResults) Delegate.Combine( delegates ); + Delegate[] chain = chained.GetInvocationList(); + double accumulator = 0; + for( int i = 0; i < chain.Length; ++i ) { + ProcessResults current = (ProcessResults) chain[i]; + accumulator += current( 4, 5 ); + } + + Console.WriteLine( "Output: {0}", accumulator ); + } +} diff --git a/10_delegates/events_1.cs b/10_delegates/events_1.cs new file mode 100644 index 0000000..b88ef7c --- /dev/null +++ b/10_delegates/events_1.cs @@ -0,0 +1,58 @@ +using System; + +// Arguments passed from UI when play event occurs. +public class PlayEventArgs : EventArgs +{ + public PlayEventArgs( string filename ) { + this.filename = filename; + } + + private string filename; + public string Filename { + get { return filename; } + } +} + +public class PlayerUI +{ + // define event for play notifications. + public event EventHandler PlayEvent; + + public void UserPressedPlay() { + OnPlay(); + } + + protected virtual void OnPlay() { + // fire the event. + EventHandler localHandler + = PlayEvent; + if( localHandler != null ) { + localHandler( this, + new PlayEventArgs("somefile.wav") ); + } + } +} + +public class CorePlayer +{ + public CorePlayer() { + ui = new PlayerUI(); + + // Register our event handler. + ui.PlayEvent += this.PlaySomething; + } + + private void PlaySomething( object source, + PlayEventArgs args ) { + // Play the file. + } + + private PlayerUI ui; +} + +public class EntryPoint +{ + static void Main() { + CorePlayer player = new CorePlayer(); + } +} diff --git a/10_delegates/events_2.cs b/10_delegates/events_2.cs new file mode 100644 index 0000000..55fbba5 --- /dev/null +++ b/10_delegates/events_2.cs @@ -0,0 +1,68 @@ +using System; + +// Arguments passed from UI when play event occurs. +public class PlayEventArgs : EventArgs +{ + public PlayEventArgs( string filename ) { + this.filename = filename; + } + + private string filename; + public string Filename { + get { return filename; } + } +} + +public class PlayerUI +{ + // define event for play notifications. + private EventHandler playEvent; + public event EventHandler PlayEvent { + add { + playEvent = (EventHandler) + Delegate.Combine( playEvent, value ); + } + remove { + playEvent = (EventHandler) + Delegate.Remove( playEvent, value ); + } + } + + public void UserPressedPlay() { + OnPlay(); + } + + protected virtual void OnPlay() { + // fire the event. + EventHandler localHandler + = playEvent; + if( localHandler != null ) { + localHandler( this, + new PlayEventArgs("somefile.wav") ); + } + } +} + +public class CorePlayer +{ + public CorePlayer() { + ui = new PlayerUI(); + + // Register our event handler. + ui.PlayEvent += this.PlaySomething; + } + + private void PlaySomething( object source, + PlayEventArgs args ) { + // Play the file. + } + + private PlayerUI ui; +} + +public class EntryPoint +{ + static void Main() { + CorePlayer player = new CorePlayer(); + } +} diff --git a/10_delegates/open_instance_1.cs b/10_delegates/open_instance_1.cs new file mode 100644 index 0000000..981eb95 --- /dev/null +++ b/10_delegates/open_instance_1.cs @@ -0,0 +1,53 @@ +using System; +using System.Reflection; +using System.Collections.Generic; + +delegate void ApplyRaiseDelegate( Employee emp, + Decimal percent ); + +public class Employee +{ + private Decimal salary; + + public Employee( Decimal salary ) { + this.salary = salary; + } + + public Decimal Salary { + get { + return salary; + } + } + + public void ApplyRaiseOf( Decimal percent ) { + salary *= (1 + percent); + } +} + +public class EntryPoint +{ + static void Main() { + List employees = new List(); + + employees.Add( new Employee(40000) ); + employees.Add( new Employee(65000) ); + employees.Add( new Employee(95000) ); + + // Create open instance delegate + MethodInfo mi = + typeof(Employee).GetMethod( "ApplyRaiseOf", + BindingFlags.Public | + BindingFlags.Instance ); + ApplyRaiseDelegate applyRaise = (ApplyRaiseDelegate ) + Delegate.CreateDelegate( typeof(ApplyRaiseDelegate), + mi ); + + // Apply raise. + foreach( Employee e in employees ) { + applyRaise( e, (Decimal) 0.10 ); + + // Send new salary to console. + Console.WriteLine( e.Salary ); + } + } +} diff --git a/10_delegates/open_instance_2.cs b/10_delegates/open_instance_2.cs new file mode 100644 index 0000000..abd9b44 --- /dev/null +++ b/10_delegates/open_instance_2.cs @@ -0,0 +1,55 @@ +using System; +using System.Reflection; +using System.Collections.Generic; + +delegate void ApplyRaiseDelegate( T instance, + Decimal percent ); + +public class Employee +{ + private Decimal salary; + + public Employee( Decimal salary ) { + this.salary = salary; + } + + public Decimal Salary { + get { + return salary; + } + } + + public void ApplyRaiseOf( Decimal percent ) { + salary *= (1 + percent); + } +} + +public class EntryPoint +{ + static void Main() { + List employees = new List(); + + employees.Add( new Employee(40000) ); + employees.Add( new Employee(65000) ); + employees.Add( new Employee(95000) ); + + // Create open instance delegate + MethodInfo mi = + typeof(Employee).GetMethod( "ApplyRaiseOf", + BindingFlags.Public | + BindingFlags.Instance ); + ApplyRaiseDelegate applyRaise = + (ApplyRaiseDelegate ) + Delegate.CreateDelegate( + typeof(ApplyRaiseDelegate), + mi ); + + // Apply raise. + foreach( Employee e in employees ) { + applyRaise( e, (Decimal) 0.10 ); + + // Send new salary to console. + Console.WriteLine( e.Salary ); + } + } +} diff --git a/10_delegates/strategy_1.cs b/10_delegates/strategy_1.cs new file mode 100644 index 0000000..283f44b --- /dev/null +++ b/10_delegates/strategy_1.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections; + +public delegate Array SortStrategy( ICollection theCollection ); + +public class Consumer +{ + public Consumer( SortStrategy defaultStrategy ) { + this.strategy = defaultStrategy; + } + + private SortStrategy strategy; + public SortStrategy Strategy { + get { return strategy; } + set { strategy = value; } + } + + public void DoSomeWork() { + // Employ the strategy. + Array sorted = strategy( myCollection ); + + // Do something with the results. + } + + private ArrayList myCollection; +} + +public class SortAlgorithms +{ + static Array SortFast( ICollection theCollection ) { + // Do the fast sort. + } + + static Array SortSlow( ICollection theCollection ) { + // Do the slow sort. + } +} diff --git a/11_generics/10_constraints_1.cs b/11_generics/10_constraints_1.cs new file mode 100644 index 0000000..bf4b64f --- /dev/null +++ b/11_generics/10_constraints_1.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; + +public interface IShape +{ + double Area { + get; + } +} + +public class Circle : IShape +{ + public Circle( double radius ) { + this.radius = radius; + } + + public double Area { + get { + return 3.1415*radius*radius; + } + } + + private double radius; +} + +public class Rect : IShape +{ + public Rect( double width, double height ) { + this.width = width; + this.height = height; + } + + public double Area { + get { + return width*height; + } + } + + private double width; + private double height; +} + +public class Shapes +{ + public double TotalArea { + get { + double acc = 0; + foreach( T shape in shapes ) { + // THIS WON'T COMPILE!!! + acc += shape.Area; + } + return acc; + } + } + + public void Add( T shape ) { + shapes.Add( shape ); + } + + private List shapes = new List(); +} + +public class EntryPoint +{ + static void Main() { + Shapes shapes = new Shapes(); + + shapes.Add( new Circle(2) ); + shapes.Add( new Rect(3, 5) ); + + Console.WriteLine( "Total Area: {0}", + shapes.TotalArea ); + } +} diff --git a/11_generics/10_constraints_2.cs b/11_generics/10_constraints_2.cs new file mode 100644 index 0000000..dc7eb87 --- /dev/null +++ b/11_generics/10_constraints_2.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; + +public interface IShape +{ + double Area { + get; + } +} + +public class Circle : IShape +{ + public Circle( double radius ) { + this.radius = radius; + } + + public double Area { + get { + return 3.1415*radius*radius; + } + } + + private double radius; +} + +public class Rect : IShape +{ + public Rect( double width, double height ) { + this.width = width; + this.height = height; + } + + public double Area { + get { + return width*height; + } + } + + private double width; + private double height; +} + +public class Shapes +{ + public double TotalArea { + get { + double acc = 0; + foreach( T shape in shapes ) { + // DON'T DO THIS!!! + IShape theShape = (IShape) shape; + acc += theShape.Area; + } + return acc; + } + } + + public void Add( T shape ) { + shapes.Add( shape ); + } + + private List shapes = new List(); +} + +public class EntryPoint +{ + static void Main() { + Shapes shapes = new Shapes(); + + shapes.Add( new Circle(2) ); + shapes.Add( new Rect(3, 5) ); + + Console.WriteLine( "Total Area: {0}", + shapes.TotalArea ); + } +} diff --git a/11_generics/10_constraints_3.cs b/11_generics/10_constraints_3.cs new file mode 100644 index 0000000..c892160 --- /dev/null +++ b/11_generics/10_constraints_3.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; + +public interface IShape +{ + double Area { + get; + } +} + +public class Circle : IShape +{ + public Circle( double radius ) { + this.radius = radius; + } + + public double Area { + get { + return 3.1415*radius*radius; + } + } + + private double radius; +} + +public class Rect : IShape +{ + public Rect( double width, double height ) { + this.width = width; + this.height = height; + } + + public double Area { + get { + return width*height; + } + } + + private double width; + private double height; +} + +public class Shapes + where T: IShape +{ + public double TotalArea { + get { + double acc = 0; + foreach( T shape in shapes ) { + acc += shape.Area; + } + return acc; + } + } + + public void Add( T shape ) { + shapes.Add( shape ); + } + + private List shapes = new List(); +} + +public class EntryPoint +{ + static void Main() { + Shapes shapes = new Shapes(); + + shapes.Add( new Circle(2) ); + shapes.Add( new Rect(3, 5) ); + + Console.WriteLine( "Total Area: {0}", + shapes.TotalArea ); + } +} diff --git a/11_generics/10_constraints_examples_1.cs b/11_generics/10_constraints_examples_1.cs new file mode 100644 index 0000000..11debb9 --- /dev/null +++ b/11_generics/10_constraints_examples_1.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; + +public class MyValueList + where T: struct +// But can't do the following +// where T: struct, new() +{ + public void Add( T v ) { + imp.Add( v ); + } + + private List imp = new List(); +} + +public class EntryPoint +{ + static void Main() { + MyValueList intList = + new MyValueList(); + + intList.Add( 123 ); + + // CAN'T DO THIS. + // MyValueList objList = + // new MyValueList(); + } +} diff --git a/11_generics/10_constraints_examples_2.cs b/11_generics/10_constraints_examples_2.cs new file mode 100644 index 0000000..12a63d3 --- /dev/null +++ b/11_generics/10_constraints_examples_2.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; + +public interface IValue +{ + // IValue methods. +} + +public class MyDictionary + where TKey: struct, IComparable + where TValue: IValue, new() +{ + public void Add( TKey key, TValue val ) { + imp.Add( key, val ); + } + + private Dictionary imp + = new Dictionary(); +} diff --git a/11_generics/10_default_value_1.cs b/11_generics/10_default_value_1.cs new file mode 100644 index 0000000..3750440 --- /dev/null +++ b/11_generics/10_default_value_1.cs @@ -0,0 +1,40 @@ +using System; + +public class MyContainer +{ + public MyContainer() { + // Create initial capacity. + imp = new T[ 4 ]; + for( int i = 0; i < imp.Length; ++i ) { + imp[i] = default(T); + } + } + + public bool IsNull( int i ) { + if( i < 0 || i >= imp.Length ) { + throw new ArgumentOutOfRangeException(); + } + + if( imp[i] == null ) { + return true; + } else { + return false; + } + } + + private T[] imp; +} + +public class EntryPoint +{ + static void Main() { + MyContainer intColl = + new MyContainer(); + + MyContainer objColl = + new MyContainer(); + + Console.WriteLine( intColl.IsNull(0) ); + Console.WriteLine( objColl.IsNull(0) ); + } +} diff --git a/11_generics/10_default_value_2.cs b/11_generics/10_default_value_2.cs new file mode 100644 index 0000000..e047f78 --- /dev/null +++ b/11_generics/10_default_value_2.cs @@ -0,0 +1,40 @@ +using System; + +public class MyContainer +{ + public MyContainer() { + // Create initial capacity. + imp = new T[ 4 ]; + for( int i = 0; i < imp.Length; ++i ) { + imp[i] = default(T); + } + } + + public bool IsNull( int i ) { + if( i < 0 || i >= imp.Length ) { + throw new ArgumentOutOfRangeException(); + } + + if( Object.Equals(imp[i], default(T)) ) { + return true; + } else { + return false; + } + } + + private T[] imp; +} + +public class EntryPoint +{ + static void Main() { + MyContainer intColl = + new MyContainer(); + + MyContainer objColl = + new MyContainer(); + + Console.WriteLine( intColl.IsNull(0) ); + Console.WriteLine( objColl.IsNull(0) ); + } +} diff --git a/11_generics/10_delegate_constraint.cs b/11_generics/10_delegate_constraint.cs new file mode 100644 index 0000000..70b786d --- /dev/null +++ b/11_generics/10_delegate_constraint.cs @@ -0,0 +1,22 @@ +using System; + +public delegate R Operation( T1 val1, + T2 val2 ) + where T1: struct + where T2: struct + where R: struct; + +public class EntryPoint +{ + public static double Add( int val1, float val2 ) { + return val1 + val2; + } + + static void Main() { + Operation op = + new Operation( EntryPoint.Add ); + + Console.WriteLine( "{0} + {1} = {2}", + 1, 3.2, op(1, 3.2f) ); + } +} diff --git a/11_generics/10_dynamic_closed_1.cs b/11_generics/10_dynamic_closed_1.cs new file mode 100644 index 0000000..526134c --- /dev/null +++ b/11_generics/10_dynamic_closed_1.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + IList intList = + (IList) CreateClosedType( typeof(List<>) ); + + IList doubleList = + (IList) + CreateClosedType( typeof(List<>) ); + + Console.WriteLine( intList ); + Console.WriteLine( doubleList ); + } + + static object CreateClosedType( Type genericType ) { + Type[] typeArguments = { + typeof( T ) + }; + + Type closedType = + genericType.MakeGenericType( typeArguments ); + + return Activator.CreateInstance( closedType ); + } +} diff --git a/11_generics/10_enumerable_1.cs b/11_generics/10_enumerable_1.cs new file mode 100644 index 0000000..7efabf5 --- /dev/null +++ b/11_generics/10_enumerable_1.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +public class MyContainer : IEnumerable +{ + public void Add( T item ) { + impl.Add( item ); + } + + public void Add( MyContainer otherContainer, + Converter converter ) { + foreach( R item in otherContainer ) { + impl.Add( converter(item) ); + } + } + + public IEnumerator GetEnumerator() { + foreach( T item in impl ) { + yield return item; + } + } + + System.Collections.IEnumerator + System.Collections.IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + private List impl = new List(); +} + diff --git a/11_generics/10_example_1.cs b/11_generics/10_example_1.cs new file mode 100644 index 0000000..865d9af --- /dev/null +++ b/11_generics/10_example_1.cs @@ -0,0 +1,7 @@ +public class MyCollection +{ + public MyCollection() { + } + + private T[] storage; +} diff --git a/11_generics/10_generic_accessibility_1.cs b/11_generics/10_generic_accessibility_1.cs new file mode 100644 index 0000000..50f3af7 --- /dev/null +++ b/11_generics/10_generic_accessibility_1.cs @@ -0,0 +1,13 @@ +public class Outer +{ + private class Nested + { + } + + public class GenericNested + { + } + + private GenericNested field1; + public GenericNested field2; // Ooops! +} diff --git a/11_generics/10_generic_delegate_1.cs b/11_generics/10_generic_delegate_1.cs new file mode 100644 index 0000000..422c54b --- /dev/null +++ b/11_generics/10_generic_delegate_1.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; + +public delegate void MyDelegate( T i ); + +public class DelegateContainer +{ + public void Add( MyDelegate del ) { + imp.Add( del ); + } + + public void CallDelegates( T k ) { + foreach( MyDelegate del in imp ) { + del( k ); + } + } + + private List > imp = new List >(); +} + +public class EntryPoint +{ + static void Main() { + DelegateContainer delegates = + new DelegateContainer(); + + delegates.Add( EntryPoint.PrintInt ); + delegates.CallDelegates( 42 ); + } + + static void PrintInt( int i ) { + Console.WriteLine( i ); + } +} diff --git a/11_generics/10_generic_problems_1.cs b/11_generics/10_generic_problems_1.cs new file mode 100644 index 0000000..e872c15 --- /dev/null +++ b/11_generics/10_generic_problems_1.cs @@ -0,0 +1,31 @@ +using System; + +public struct Complex + where T: struct +{ + public Complex( T real, T imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public T Real { + get { return real; } + set { real = value; } + } + + public T Img { + get { return imaginary; } + set { imaginary = value; } + } + + private T real; + private T imaginary; +} + +public class EntryPoint +{ + static void Main() { + Complex c = + new Complex( 4, 5 ); + } +} diff --git a/11_generics/10_generic_problems_2.cs b/11_generics/10_generic_problems_2.cs new file mode 100644 index 0000000..3ab63a4 --- /dev/null +++ b/11_generics/10_generic_problems_2.cs @@ -0,0 +1,42 @@ +using System; + +public struct Complex + where T: struct +{ + public Complex( T real, T imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public T Real { + get { return real; } + set { real = value; } + } + + public T Img { + get { return imaginary; } + set { imaginary = value; } + } + + public T Magnitude { + get { + // WON'T COMPILE!!! + return Math.Sqrt( real * real + + imaginary * imaginary ); + } + } + + private T real; + private T imaginary; +} + +public class EntryPoint +{ + static void Main() { + Complex c = + new Complex( 3, 4 ); + + Console.WriteLine( "Magnitude is {0}", + c.Magnitude ); + } +} diff --git a/11_generics/10_generic_problems_3.cs b/11_generics/10_generic_problems_3.cs new file mode 100644 index 0000000..f71b09d --- /dev/null +++ b/11_generics/10_generic_problems_3.cs @@ -0,0 +1,71 @@ +using System; + +public struct Complex + where T: struct, IConvertible +{ + // Delegate for doing multiplication. + public delegate T BinaryOp( T val1, T val2 ); + + public Complex( T real, T imaginary, + BinaryOp mult, + BinaryOp add, + Converter convToT ) { + this.real = real; + this.imaginary = imaginary; + this.mult = mult; + this.add = add; + this.convToT = convToT; + } + + public T Real { + get { return real; } + set { real = value; } + } + + public T Img { + get { return imaginary; } + set { imaginary = value; } + } + + public T Magnitude { + get { + double magnitude = + Math.Sqrt( Convert.ToDouble(add(mult(real, real), + mult(imaginary, imaginary))) ); + return convToT( magnitude ); + } + } + + private T real; + private T imaginary; + private BinaryOp mult; + private BinaryOp add; + private Converter convToT; +} + +public class EntryPoint +{ + static void Main() { + Complex c = + new Complex( + 3, 4, + EntryPoint.MultiplyInt64, + EntryPoint.AddInt64, + EntryPoint.DoubleToInt64 ); + + Console.WriteLine( "Magnitude is {0}", + c.Magnitude ); + } + + static Int64 MultiplyInt64( Int64 val1, Int64 val2 ) { + return val1 * val2; + } + + static Int64 AddInt64( Int64 val1, Int64 val2 ) { + return val1 + val2; + } + + static Int64 DoubleToInt64( double d ) { + return Convert.ToInt64( d ); + } +} diff --git a/11_generics/10_generic_problems_4.cs b/11_generics/10_generic_problems_4.cs new file mode 100644 index 0000000..9adbc06 --- /dev/null +++ b/11_generics/10_generic_problems_4.cs @@ -0,0 +1,75 @@ +using System; + +public struct Complex : IComparable > + where T: struct, IConvertible, IComparable +{ + // Delegate for doing multiplication. + public delegate T BinaryOp( T val1, T val2 ); + + public Complex( T real, T imaginary, + BinaryOp mult, + BinaryOp add, + Converter convToT ) { + this.real = real; + this.imaginary = imaginary; + this.mult = mult; + this.add = add; + this.convToT = convToT; + } + + public T Real { + get { return real; } + set { real = value; } + } + + public T Img { + get { return imaginary; } + set { imaginary = value; } + } + + public T Magnitude { + get { + double magnitude = + Math.Sqrt( Convert.ToDouble(add(mult(real, real), + mult(imaginary, imaginary))) ); + return convToT( magnitude ); + } + } + + public int CompareTo( Complex other ) { + return Magnitude.CompareTo( other.Magnitude ); + } + + private T real; + private T imaginary; + private BinaryOp mult; + private BinaryOp add; + private Converter convToT; +} + +public class EntryPoint +{ + static void Main() { + Complex c = + new Complex( + 3, 4, + EntryPoint.MultiplyInt64, + EntryPoint.AddInt64, + EntryPoint.DoubleToInt64 ); + + Console.WriteLine( "Magnitude is {0}", + c.Magnitude ); + } + + static Int64 MultiplyInt64( Int64 val1, Int64 val2 ) { + return val1 * val2; + } + + static Int64 AddInt64( Int64 val1, Int64 val2 ) { + return val1 + val2; + } + + static Int64 DoubleToInt64( double d ) { + return Convert.ToInt64( d ); + } +} diff --git a/11_generics/10_generic_problems_5.cs b/11_generics/10_generic_problems_5.cs new file mode 100644 index 0000000..4b4a7e2 --- /dev/null +++ b/11_generics/10_generic_problems_5.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; + +public struct Complex : IComparable > + where T: struct +{ + // Delegate for doing multiplication. + public delegate T BinaryOp( T val1, T val2 ); + + public Complex( T real, T imaginary, + BinaryOp mult, + BinaryOp add, + Converter convToT ) { + this.real = real; + this.imaginary = imaginary; + this.mult = mult; + this.add = add; + this.convToT = convToT; + } + + public T Real { + get { return real; } + set { real = value; } + } + + public T Img { + get { return imaginary; } + set { imaginary = value; } + } + + public T Magnitude { + get { + double magnitude = + Math.Sqrt( Convert.ToDouble(add(mult(real, real), + mult(imaginary, imaginary))) ); + return convToT( magnitude ); + } + } + + public int CompareTo( Complex other ) { + return Comparer.Default.Compare( this.Magnitude, other.Magnitude ); + } + + private T real; + private T imaginary; + private BinaryOp mult; + private BinaryOp add; + private Converter convToT; +} + +public class EntryPoint +{ + static void Main() { + Complex c = + new Complex( + 3, 4, + EntryPoint.MultiplyInt64, + EntryPoint.AddInt64, + EntryPoint.DoubleToInt64 ); + + Console.WriteLine( "Magnitude is {0}", + c.Magnitude ); + } + + static void DummyMethod( Complex > c ) { + } + + static Int64 AddInt64( Int64 val1, Int64 val2 ) { + return val1 + val2; + } + + static Int64 MultiplyInt64( Int64 val1, Int64 val2 ) { + return val1 * val2; + } + + static Int64 DoubleToInt64( double d ) { + return Convert.ToInt64( d ); + } +} diff --git a/11_generics/10_generic_problems_6.cs b/11_generics/10_generic_problems_6.cs new file mode 100644 index 0000000..d09cd48 --- /dev/null +++ b/11_generics/10_generic_problems_6.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; + +public struct Complex : IComparable > + where T: struct +{ + // Delegate for doing multiplication. + public delegate T BinaryOp( T val1, T val2 ); + + public Complex( T real, T imaginary, + BinaryOp mult, + BinaryOp add, + Converter convToDouble, + Converter convToT ) { + this.real = real; + this.imaginary = imaginary; + this.mult = mult; + this.add = add; + this.convToDouble = convToDouble; + this.convToT = convToT; + } + + public T Real { + get { return real; } + set { real = value; } + } + + public T Img { + get { return imaginary; } + set { imaginary = value; } + } + + public T Magnitude { + get { + double magnitude = + Math.Sqrt( convToDouble(add(mult(real, real), + mult(imaginary, imaginary))) ); + return convToT( magnitude ); + } + } + + public int CompareTo( Complex other ) { + return Comparer.Default.Compare( this.Magnitude, other.Magnitude ); + } + + private T real; + private T imaginary; + private BinaryOp mult; + private BinaryOp add; + private Converter convToDouble; + private Converter convToT; +} + +public class EntryPoint +{ + static void Main() { + Complex c = + new Complex( + 3, 4, + EntryPoint.MultiplyInt64, + EntryPoint.AddInt64, + EntryPoint.Int64ToDouble, + EntryPoint.DoubleToInt64 ); + + Console.WriteLine( "Magnitude is {0}", + c.Magnitude ); + } + + static void DummyMethod( Complex > c ) { + } + + static Int64 MultiplyInt64( Int64 val1, Int64 val2 ) { + return val1 * val2; + } + + static Int64 AddInt64( Int64 val1, Int64 val2 ) { + return val1 + val2; + } + + static Int64 DoubleToInt64( double d ) { + return Convert.ToInt64( d ); + } + + static double Int64ToDouble( Int64 i ) { + return Convert.ToDouble( i ); + } +} diff --git a/11_generics/10_generic_sorted_list_1.cs b/11_generics/10_generic_sorted_list_1.cs new file mode 100644 index 0000000..b9a1dbf --- /dev/null +++ b/11_generics/10_generic_sorted_list_1.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + SortedList list1 = + new SortedList(); + + SortedList list2 = + new SortedList( Comparer.Default ); + + list1.Add( 1, "one" ); + list1.Add( 2, "two" ); + list2.Add( 3, "three" ); + list2.Add( 4, "four" ); + } +} diff --git a/11_generics/10_generic_vs_nongeneric.cs b/11_generics/10_generic_vs_nongeneric.cs new file mode 100644 index 0000000..b5fe2e5 --- /dev/null +++ b/11_generics/10_generic_vs_nongeneric.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + } + + public void NonGeneric( Stack stack ) { + foreach( object o in stack ) { + int number = (int) o; + Console.WriteLine( number ); + } + } + + public void Generic( Stack stack ) { + foreach( int number in stack ) { + Console.WriteLine( number ); + } + } +} diff --git a/11_generics/10_needs_constraints.cs b/11_generics/10_needs_constraints.cs new file mode 100644 index 0000000..4e06522 --- /dev/null +++ b/11_generics/10_needs_constraints.cs @@ -0,0 +1,26 @@ +using System; + +public class ContainedClass +{ + public long GetSomeValue() { + return 42; + } +} + +public class MyClass +{ + public void DoSomething() { + Console.WriteLine( field1.GetHashCode() ); + Console.WriteLine( field1.GetSomeValue() ); + } + + private T field1; +} + +public class EntryPoint +{ + static void Main() { + MyClass obj1 = new MyClass(); + MyClass obj2 = new MyClass(); + } +} diff --git a/11_generics/10_no_delegate_for_type_argument.cs b/11_generics/10_no_delegate_for_type_argument.cs new file mode 100644 index 0000000..bf66161 --- /dev/null +++ b/11_generics/10_no_delegate_for_type_argument.cs @@ -0,0 +1,34 @@ +// THIS WON'T WORK AS EXPECTED!!! +using System; +using System.Collections.Generic; + +public delegate void MyDelegate( int i ); + +public class DelegateContainer +{ + public void Add( T del ) { + imp.Add( del ); + } + + public void CallDelegates( int k ) { + foreach( T del in imp ) { +// del( k ); + } + } + + private List imp = new List(); +} + +public class EntryPoint +{ + static void Main() { + DelegateContainer delegates = + new DelegateContainer(); + + delegates.Add( EntryPoint.PrintInt ); + } + + static void PrintInt( int i ) { + Console.WriteLine( i ); + } +} diff --git a/11_generics/10_nullable_1.cs b/11_generics/10_nullable_1.cs new file mode 100644 index 0000000..1120e9f --- /dev/null +++ b/11_generics/10_nullable_1.cs @@ -0,0 +1,40 @@ +using System; + +public class Employee +{ + public Employee( string firstName, + string lastName ) { + this.firstName = firstName; + this.lastName = lastName; + + this.terminationDate = null; + this.ssn = default(Nullable); + } + + public string firstName; + public string lastName; + + public Nullable terminationDate; + public long? ssn; // Shorthand notation +} + +public class EntryPoint +{ + static void Main() { + Employee emp = new Employee( "Vasya", + "Pupkin" ); + emp.ssn = 1234567890; + + Console.WriteLine( "{0} {1}", + emp.firstName, + emp.lastName ); + if( emp.terminationDate.HasValue ) { + Console.WriteLine( "Start Date: {0}", + emp.terminationDate ); + } + + long tempSSN = emp.ssn ?? -1; + Console.WriteLine( "SSN: {0}", + tempSSN ); + } +} diff --git a/11_generics/10_template_derivation.cpp b/11_generics/10_template_derivation.cpp new file mode 100644 index 0000000..63f3d77 --- /dev/null +++ b/11_generics/10_template_derivation.cpp @@ -0,0 +1,24 @@ +class Employee +{ + public: + long get_salary() { + return salary; + } + void set_salary( long salary ) { + this->salary = salary; + } + + private: + long salary; +}; + +template< class T > +class MyClass : public T +{ +}; + +void main() +{ + MyClass myInstance; + myInstance.get_salary(); +} diff --git a/11_generics/10_template_method_1.cs b/11_generics/10_template_method_1.cs new file mode 100644 index 0000000..9d150b5 --- /dev/null +++ b/11_generics/10_template_method_1.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; + +public class MyContainer : IEnumerable +{ + public void Add( T item ) { + impl.Add( item ); + } + + // Converter is a new delegate type introduced + // in the .NET Framework that can be wired up to a method that + // knows how to convert the TInput type into a TOutput type. + public void Add( MyContainer otherContainer, + Converter converter ) { + foreach( R item in otherContainer ) { + impl.Add( converter(item) ); + } + } + + public IEnumerator GetEnumerator() { + foreach( T item in impl ) { + yield return item; + } + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + private List impl = new List(); +} + +public class EntryPoint +{ + static void Main() { + MyContainer lContainer = new MyContainer(); + MyContainer iContainer = new MyContainer(); + + lContainer.Add( 1 ); + lContainer.Add( 2 ); + iContainer.Add( 3 ); + iContainer.Add( 4 ); + + lContainer.Add( iContainer, + EntryPoint.IntToLongConverter ); + + foreach( long l in lContainer ) { + Console.WriteLine( l ); + } + } + + static long IntToLongConverter( int i ) { + return i; + } +} diff --git a/12_threading/async_1.cs b/12_threading/async_1.cs new file mode 100644 index 0000000..9e742bd --- /dev/null +++ b/12_threading/async_1.cs @@ -0,0 +1,39 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + // Declare the delegate for the async call. + private delegate Decimal ComputeTaxesDelegate( int year ); + + // The method that computes the taxes. + private static Decimal ComputeTaxes( int year ) { + Console.WriteLine( "Computing taxes in thread {0}", + Thread.CurrentThread.GetHashCode() ); + + // Here's where the long calculation happens. + Thread.Sleep( 6000 ); + + // You owe the man. + return 4356.98M; + } + + static void Main() { + // Let's make the asynchronous call by creating + // the delegate and calling it. + ComputeTaxesDelegate work = + new ComputeTaxesDelegate( EntryPoint.ComputeTaxes ); + IAsyncResult pendingOp = work.BeginInvoke( 2004, + null, + null ); + + // Do some other useful work. + Thread.Sleep( 3000 ); + + // Finish the async call. + Console.WriteLine( "Waiting for operation to complete." ); + Decimal result = work.EndInvoke( pendingOp ); + + Console.WriteLine( "Taxes owed: {0}", result ); + } +} diff --git a/12_threading/async_2.cs b/12_threading/async_2.cs new file mode 100644 index 0000000..1311041 --- /dev/null +++ b/12_threading/async_2.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + // Declare the delegate for the async call. + private delegate Decimal ComputeTaxesDelegate( int year ); + + // The method that computes the taxes. + private static Decimal ComputeTaxes( int year ) { + Console.WriteLine( "Computing taxes in thread {0}", + Thread.CurrentThread.GetHashCode() ); + + // Here's where the long calculation happens. + Thread.Sleep( 6000 ); + + // You owe the man. + return 4356.98M; + } + + private static void TaxesComputed( IAsyncResult ar ) { + // Let' get the results now. + ComputeTaxesDelegate work = + (ComputeTaxesDelegate) ar.AsyncState; + + Decimal result = work.EndInvoke( ar ); + Console.WriteLine( "Taxes owed: {0}", result ); + } + + static void Main() { + // Let's make the asynchronous call by creating + // the delegate and calling it. + ComputeTaxesDelegate work = + new ComputeTaxesDelegate( EntryPoint.ComputeTaxes ); + work.BeginInvoke( 2004, + new AsyncCallback( + EntryPoint.TaxesComputed), + work ); + + // Do some other useful work. + Thread.Sleep( 3000 ); + + Console.WriteLine( "Waiting for operation to complete." ); + Thread.Sleep( 4000 ); + } +} diff --git a/12_threading/async_3.cs b/12_threading/async_3.cs new file mode 100644 index 0000000..47ed373 --- /dev/null +++ b/12_threading/async_3.cs @@ -0,0 +1,41 @@ +using System; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; + +public class EntryPoint { + private const int CONNECT_QUEUE_LENGTH = 4; + private const int LISTEN_PORT = 1234; + + static void ListenForRequests() { + Socket listenSock = + new Socket( AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp ); + listenSock.Bind( new IPEndPoint(IPAddress.Any, + LISTEN_PORT) ); + listenSock.Listen( CONNECT_QUEUE_LENGTH ); + + while( true ) { + using( Socket newConnection = listenSock.Accept() ) { + // Send the data. + byte[] msg = + Encoding.UTF8.GetBytes( "Hello World!" ); + newConnection.Send( msg, SocketFlags.None ); + } + } + } + + static void Main() { + // Start the listening thread. + Thread listener = new Thread( + new ThreadStart( + EntryPoint.ListenForRequests) ); + listener.IsBackground = true; + listener.Start(); + + Console.WriteLine( "Press to quit" ); + Console.ReadLine(); + } +} diff --git a/12_threading/async_4.cs b/12_threading/async_4.cs new file mode 100644 index 0000000..67f8a71 --- /dev/null +++ b/12_threading/async_4.cs @@ -0,0 +1,41 @@ +using System; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; + +public class EntryPoint { + private const int CONNECT_QUEUE_LENGTH = 4; + private const int LISTEN_PORT = 1234; + + static void ListenForRequests() { + Socket listenSock = + new Socket( AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp ); + listenSock.Bind( new IPEndPoint(IPAddress.Any, + LISTEN_PORT) ); + listenSock.Listen( CONNECT_QUEUE_LENGTH ); + + while( true ) { + Socket newConnection = listenSock.Accept(); + byte[] msg = Encoding.UTF8.GetBytes( "Hello World!" ); + newConnection.BeginSend( msg, + 0, msg.Length, + SocketFlags.None, + null, null ); + } + } + + static void Main() { + // Start the listening thread. + Thread listener = new Thread( + new ThreadStart( + EntryPoint.ListenForRequests) ); + listener.IsBackground = true; + listener.Start(); + + Console.WriteLine( "Press to quit" ); + Console.ReadLine(); + } +} diff --git a/12_threading/async_5.cs b/12_threading/async_5.cs new file mode 100644 index 0000000..11f559a --- /dev/null +++ b/12_threading/async_5.cs @@ -0,0 +1,54 @@ +using System; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; + +public class EntryPoint { + private const int CONNECT_QUEUE_LENGTH = 4; + private const int LISTEN_PORT = 1234; + private const int MAX_CONNECTION_HANDLERS = 4; + + private static void HandleConnection( IAsyncResult ar ) { + Socket listener = (Socket) ar.AsyncState; + + Socket newConnection = listener.EndAccept( ar ); + byte[] msg = Encoding.UTF8.GetBytes( "Hello World!" ); + newConnection.BeginSend( msg, + 0, msg.Length, + SocketFlags.None, + new AsyncCallback( + EntryPoint.CloseConnection), + newConnection ); + + // Now queue another accept. + listener.BeginAccept( + new AsyncCallback(EntryPoint.HandleConnection), + listener ); + } + + static void CloseConnection( IAsyncResult ar ) { + Socket theSocket = (Socket) ar.AsyncState; + theSocket.Close(); + } + + static void Main() { + Socket listenSock = + new Socket( AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp ); + listenSock.Bind( new IPEndPoint(IPAddress.Any, + LISTEN_PORT) ); + listenSock.Listen( CONNECT_QUEUE_LENGTH ); + + // Pend the connection handlers. + for( int i = 0; i < MAX_CONNECTION_HANDLERS; ++i ) { + listenSock.BeginAccept( + new AsyncCallback(EntryPoint.HandleConnection), + listenSock ); + } + + Console.WriteLine( "Press to quit" ); + Console.ReadLine(); + } +} diff --git a/12_threading/foreground_1.cs b/12_threading/foreground_1.cs new file mode 100644 index 0000000..ba1becc --- /dev/null +++ b/12_threading/foreground_1.cs @@ -0,0 +1,20 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + private static void ThreadFunc1() { + Thread.Sleep( 5000 ); + Console.WriteLine( "Exiting extra thread" ); + } + + static void Main() { + Thread thread1 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc1) ); + + thread1.Start(); + + Console.WriteLine( "Exiting main thread" ); + } +} + diff --git a/12_threading/interlocked_1.cs b/12_threading/interlocked_1.cs new file mode 100644 index 0000000..b273889 --- /dev/null +++ b/12_threading/interlocked_1.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + static private int numberThreads = 0; + + static private Random rnd = new Random(); + + private static void RndThreadFunc() { + // Manage thread count and wait for a + // random amount of time between 1 and 12 + // seconds. + Interlocked.Increment( ref numberThreads ); + try { + int time = rnd.Next( 1000, 12000 ); + Thread.Sleep( time ); + } + finally { + Interlocked.Decrement( ref numberThreads ); + } + } + + private static void RptThreadFunc() { + while( true ) { + int threadCount = 0; + threadCount = + Interlocked.Exchange( ref numberThreads, + numberThreads ); + Console.WriteLine( "{0} thread(s) alive", + threadCount ); + Thread.Sleep( 1000 ); + } + } + + static void Main() { + // Start the reporting threads. + Thread reporter = + new Thread( new ThreadStart( + EntryPoint.RptThreadFunc) ); + reporter.IsBackground = true; + reporter.Start(); + + // Start the threads that wait random time. + Thread[] rndthreads = new Thread[ 50 ]; + for( uint i = 0; i < 50; ++i ) { + rndthreads[i] = + new Thread( new ThreadStart( + EntryPoint.RndThreadFunc) ); + rndthreads[i].Start(); + } + } +} diff --git a/12_threading/interlocked_2.cs b/12_threading/interlocked_2.cs new file mode 100644 index 0000000..f27f9c5 --- /dev/null +++ b/12_threading/interlocked_2.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using System.Threading; + +public class SpinLock +{ + public SpinLock( int spinWait ) { + this.spinWait = spinWait; + } + + public void Enter() { + while( Interlocked.CompareExchange(ref theLock, + 1, + 0) == 1 ) { + // The lock is taken, spin. + Thread.Sleep( spinWait ); + } + } + + public void Exit() { + // Reset the lock. + Interlocked.Exchange( ref theLock, + 0 ); + } + + private int theLock = 0; + private int spinWait; +} + +public class SpinLockManager : IDisposable +{ + public SpinLockManager( SpinLock spinLock ) { + this.spinLock = spinLock; + spinLock.Enter(); + } + + public void Dispose() { + spinLock.Exit(); + } + + private SpinLock spinLock; +} + +public class EntryPoint +{ + static private Random rnd = new Random(); + private static SpinLock logLock = new SpinLock( 10 ); + private static StreamWriter fsLog = + new StreamWriter( File.Open("log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None) ); + + private static void RndThreadFunc() { + using( new SpinLockManager(logLock) ) { + fsLog.WriteLine( "Thread Starting" ); + fsLog.Flush(); + } + + int time = rnd.Next( 10, 200 ); + Thread.Sleep( time ); + + using( new SpinLockManager(logLock) ) { + fsLog.WriteLine( "Thread Exiting" ); + fsLog.Flush(); + } + } + + static void Main() { + // Start the threads that wait random time. + Thread[] rndthreads = new Thread[ 50 ]; + for( uint i = 0; i < 50; ++i ) { + rndthreads[i] = + new Thread( new ThreadStart( + EntryPoint.RndThreadFunc) ); + rndthreads[i].Start(); + } + } +} diff --git a/12_threading/monitor_1.cs b/12_threading/monitor_1.cs new file mode 100644 index 0000000..41dad18 --- /dev/null +++ b/12_threading/monitor_1.cs @@ -0,0 +1,68 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + static private object theLock = new Object(); + static private int numberThreads = 0; + static private Random rnd = new Random(); + + private static void RndThreadFunc() { + // Manage thread count and wait for a + // random amount of time between 1 and 12 + // seconds. + try { + Monitor.Enter( theLock ); + ++numberThreads; + } + finally { + Monitor.Exit( theLock ); + } + + int time = rnd.Next( 1000, 12000 ); + Thread.Sleep( time ); + + try { + Monitor.Enter( theLock ); + --numberThreads; + } + finally { + Monitor.Exit( theLock ); + } + } + + private static void RptThreadFunc() { + while( true ) { + int threadCount = 0; + try { + Monitor.Enter( theLock ); + threadCount = numberThreads; + } + finally { + Monitor.Exit( theLock ); + } + + Console.WriteLine( "{0} thread(s) alive", + threadCount ); + Thread.Sleep( 1000 ); + } + } + + static void Main() { + // Start the reporting threads. + Thread reporter = + new Thread( new ThreadStart( + EntryPoint.RptThreadFunc) ); + reporter.IsBackground = true; + reporter.Start(); + + // Start the threads that wait random time. + Thread[] rndthreads = new Thread[ 50 ]; + for( uint i = 0; i < 50; ++i ) { + rndthreads[i] = + new Thread( new ThreadStart( + EntryPoint.RndThreadFunc) ); + rndthreads[i].Start(); + } + } +} diff --git a/12_threading/monitor_2.cs b/12_threading/monitor_2.cs new file mode 100644 index 0000000..f103d7b --- /dev/null +++ b/12_threading/monitor_2.cs @@ -0,0 +1,56 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + static private object theLock = new Object(); + static private int numberThreads = 0; + static private Random rnd = new Random(); + + private static void RndThreadFunc() { + // Manage thread count and wait for a + // random amount of time between 1 and 12 + // seconds. + lock( theLock ) { + ++numberThreads; + } + + int time = rnd.Next( 1000, 12000 ); + Thread.Sleep( time ); + + lock( theLock ) { + --numberThreads; + } + } + + private static void RptThreadFunc() { + while( true ) { + int threadCount = 0; + lock( theLock ) { + threadCount = numberThreads; + } + + Console.WriteLine( "{0} thread(s) alive", + threadCount ); + Thread.Sleep( 1000 ); + } + } + + static void Main() { + // Start the reporting threads. + Thread reporter = + new Thread( new ThreadStart( + EntryPoint.RptThreadFunc) ); + reporter.IsBackground = true; + reporter.Start(); + + // Start the threads that wait random time. + Thread[] rndthreads = new Thread[ 50 ]; + for( uint i = 0; i < 50; ++i ) { + rndthreads[i] = + new Thread( new ThreadStart( + EntryPoint.RndThreadFunc) ); + rndthreads[i].Start(); + } + } +} diff --git a/12_threading/monitor_3.cs b/12_threading/monitor_3.cs new file mode 100644 index 0000000..9d6592f --- /dev/null +++ b/12_threading/monitor_3.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + static private int counter = 0; + + // NEVER DO THIS !!! + static private int theLock = 0; + + static private void ThreadFunc() { + for( int i = 0; i < 50; ++i ) { + Monitor.Enter( theLock ); + try { + Console.WriteLine( ++counter ); + } + finally { + Monitor.Exit( theLock ); + } + } + } + + static void Main() { + Thread thread1 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + Thread thread2 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + thread1.Start(); + thread2.Start(); + } +} diff --git a/12_threading/monitor_4.cs b/12_threading/monitor_4.cs new file mode 100644 index 0000000..bd4a4e1 --- /dev/null +++ b/12_threading/monitor_4.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + static private int counter = 0; + + static private object theLock = new Object(); + + static private void ThreadFunc1() { + lock( theLock ) { + for( int i = 0; i < 50; ++i ) { + Monitor.Wait( theLock, Timeout.Infinite ); + Console.WriteLine( "{0} from Thread {1}", + ++counter, + Thread.CurrentThread.GetHashCode() ); + Monitor.Pulse( theLock ); + } + } + } + + static private void ThreadFunc2() { + lock( theLock ) { + for( int i = 0; i < 50; ++i ) { + Monitor.Pulse( theLock ); + Monitor.Wait( theLock, Timeout.Infinite ); + Console.WriteLine( "{0} from Thread {1}", + ++counter, + Thread.CurrentThread.GetHashCode() ); + } + } + } + + static void Main() { + Thread thread1 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc1) ); + Thread thread2 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc2) ); + thread1.Start(); + thread2.Start(); + } +} diff --git a/12_threading/monitor_5.cs b/12_threading/monitor_5.cs new file mode 100644 index 0000000..94816cf --- /dev/null +++ b/12_threading/monitor_5.cs @@ -0,0 +1,84 @@ +using System; +using System.Threading; +using System.Collections; + +public class CrudeThreadPool +{ + static readonly int MAX_WORK_THREADS = 4; + static readonly int WAIT_TIMEOUT = 2000; + + public delegate void WorkDelegate(); + + public CrudeThreadPool() { + stop = 0; + workLock = new Object(); + workQueue = new Queue(); + threads = new Thread[ MAX_WORK_THREADS ]; + + for( int i = 0; i < MAX_WORK_THREADS; ++i ) { + threads[i] = + new Thread( new ThreadStart(this.ThreadFunc) ); + threads[i].Start(); + } + } + + private void ThreadFunc() { + lock( workLock ) { + int shouldStop = 0; + do { + shouldStop = Interlocked.Exchange( ref stop, + stop ); + if( shouldStop == 0 ) { + WorkDelegate workItem = null; + if( Monitor.Wait(workLock, WAIT_TIMEOUT) ) { + // Process the item on the front of the + // queue + lock( workQueue ) { + workItem = + (WorkDelegate) workQueue.Dequeue(); + } + workItem(); + } + } + } while( shouldStop == 0 ); + } + } + + public void SubmitWorkItem( WorkDelegate item ) { + lock( workLock ) { + lock( workQueue ) { + workQueue.Enqueue( item ); + } + + Monitor.Pulse( workLock ); + } + } + + public void Shutdown() { + Interlocked.Exchange( ref stop, 1 ); + } + + private Queue workQueue; + private Object workLock; + private Thread[] threads; + private int stop; +} + +public class EntryPoint +{ + static void WorkFunction() { + Console.WriteLine( "WorkFunction() called on Thread {0}", + Thread.CurrentThread.GetHashCode() ); + } + + static void Main() { + CrudeThreadPool pool = new CrudeThreadPool(); + for( int i = 0; i < 10; ++i ) { + pool.SubmitWorkItem( + new CrudeThreadPool.WorkDelegate( + EntryPoint.WorkFunction) ); + } + + pool.Shutdown(); + } +} diff --git a/12_threading/named_event_1.cs b/12_threading/named_event_1.cs new file mode 100644 index 0000000..02fa28d --- /dev/null +++ b/12_threading/named_event_1.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading; +using System.Runtime.InteropServices; +using System.ComponentModel; +using Microsoft.Win32.SafeHandles; + +public class NamedEventCreator +{ + [DllImport( "KERNEL32.DLL", EntryPoint="CreateEventW", + SetLastError=true )] + private static extern SafeWaitHandle CreateEvent( + IntPtr lpEventAttributes, + bool bManualReset, + bool bInitialState, + string lpName ); + + public const int INVALID_HANDLE_VALUE = -1; + + public static AutoResetEvent CreateAutoResetEvent( + bool initialState, + string name ) { + // Create named event. + SafeWaitHandle rawEvent = CreateEvent( IntPtr.Zero, + false, + false, + name ); + if( rawEvent.IsInvalid ) { + throw new Win32Exception( + Marshal.GetLastWin32Error() ); + } + + // Create a managed event type based on this handle. + AutoResetEvent autoEvent = new AutoResetEvent( false ); + + // Must clean up handle currently in autoEvent + // before swapping it with the named one. + autoEvent.SafeWaitHandle = rawEvent; + + return autoEvent; + } +} + diff --git a/12_threading/thread_1.cs b/12_threading/thread_1.cs new file mode 100644 index 0000000..fa9f646 --- /dev/null +++ b/12_threading/thread_1.cs @@ -0,0 +1,28 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + private static void ThreadFunc() { + Console.WriteLine( "Hello from new thread {0}!", + Thread.CurrentThread.GetHashCode() ); + } + + static void Main() { + // Create the new thread. + Thread newThread = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + + Console.WriteLine( "Main Thread is {0}", + Thread.CurrentThread.GetHashCode() ); + Console.WriteLine( "Starting new thread..." ); + + // Start the new thread. + newThread.Start(); + + // Wait for new thread to finish. + newThread.Join(); + + Console.WriteLine( "New thread has finished" ); + } +} diff --git a/12_threading/thread_2.cs b/12_threading/thread_2.cs new file mode 100644 index 0000000..e5aa945 --- /dev/null +++ b/12_threading/thread_2.cs @@ -0,0 +1,55 @@ +using System; +using System.Threading; +using System.Collections; + +public class QueueProcessor +{ + public QueueProcessor( Queue theQueue ) { + this.theQueue = theQueue; + theThread = new Thread( new ThreadStart(this.ThreadFunc) ); + } + + private Queue theQueue; + + private Thread theThread; + public Thread TheThread { + get { + return theThread; + } + } + + public void BeginProcessData() { + theThread.Start(); + } + + public void EndProcessData() { + theThread.Join(); + } + + private void ThreadFunc() { + // ... drain theQueue here. + } +} + +public class EntryPoint +{ + static void Main() { + Queue queue1 = new Queue(); + Queue queue2 = new Queue(); + + // ... operations to fill the queues with data. + + // Process each queue in a separate threda. + QueueProcessor proc1 = new QueueProcessor( queue1 ); + proc1.BeginProcessData(); + + QueueProcessor proc2 = new QueueProcessor( queue2 ); + proc2.BeginProcessData(); + + // ... do some other work in the meantime. + + // Wait for the work to finish. + proc1.EndProcessData(); + proc2.EndProcessData(); + } +} diff --git a/12_threading/thread_abort_1.cs b/12_threading/thread_abort_1.cs new file mode 100644 index 0000000..f7422d2 --- /dev/null +++ b/12_threading/thread_abort_1.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + private static void ThreadFunc() { + ulong counter = 0; + while( true ) { + try { + Console.WriteLine( "{0}", counter++ ); + } + catch( ThreadAbortException ) { + // Attempt to swallow the exception and continue. + Console.WriteLine( "Abort!" ); + } + } + } + + static void Main() { + Thread newThread = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + newThread.Start(); + Thread.Sleep( 2000 ); + + // Abort the thread. + newThread.Abort(); + + // Wait for thread to finish. + newThread.Join(); + } +} diff --git a/12_threading/timer_1.cs b/12_threading/timer_1.cs new file mode 100644 index 0000000..a86e6dd --- /dev/null +++ b/12_threading/timer_1.cs @@ -0,0 +1,25 @@ +using System; +using System.Threading; + +public class EntryPoint +{ + private static void TimerProc( object state ) { + Console.WriteLine( "The current time is {0} on thread {1}", + DateTime.Now, + Thread.CurrentThread.GetHashCode() ); + Thread.Sleep( 3000 ); + } + + static void Main() { + Console.WriteLine( "Press when finished\n\n" ); + + Timer myTimer = + new Timer( new TimerCallback(EntryPoint.TimerProc), + null, + 0, + 2000 ); + + Console.ReadLine(); + myTimer.Dispose(); + } +} diff --git a/12_threading/tls2.cs b/12_threading/tls2.cs new file mode 100644 index 0000000..92c5f16 --- /dev/null +++ b/12_threading/tls2.cs @@ -0,0 +1,48 @@ +using System; +using System.Threading; + +public class TLSClass +{ + static TLSClass() { + tlsSlot = Thread.AllocateDataSlot(); + } + + public TLSClass() { + Console.WriteLine( "Creating TLSClass" ); + } + + public static TLSClass TlsSlot { + get { + Object obj = Thread.GetData( tlsSlot ); + if( obj == null ) { + obj = new TLSClass(); + Thread.SetData( tlsSlot, obj ); + } + return (TLSClass) obj; + } + } + + private static LocalDataStoreSlot tlsSlot = null; +} + +public class EntryPoint +{ + private static void ThreadFunc() { + Console.WriteLine( "Thread {0} starting...", + Thread.CurrentThread.GetHashCode() ); + Console.WriteLine( "tlsdata for this thread is \"{0}\"", + TLSClass.TlsSlot ); + Console.WriteLine( "Thread {0} exiting", + Thread.CurrentThread.GetHashCode() ); + } + + static void Main() { + Thread thread1 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + Thread thread2 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + + thread1.Start(); + thread2.Start(); + } +} diff --git a/12_threading/tls_1.cs b/12_threading/tls_1.cs new file mode 100644 index 0000000..d1408e7 --- /dev/null +++ b/12_threading/tls_1.cs @@ -0,0 +1,37 @@ +using System; +using System.Threading; + +public class TLSClass +{ + public TLSClass() { + Console.WriteLine( "Creating TLSClass" ); + } +} + +public class TLSFieldClass +{ + [ThreadStatic] + public static TLSClass tlsdata = new TLSClass(); +} + +public class EntryPoint +{ + private static void ThreadFunc() { + Console.WriteLine( "Thread {0} starting...", + Thread.CurrentThread.GetHashCode() ); + Console.WriteLine( "tlsdata for this thread is \"{0}\"", + TLSFieldClass.tlsdata ); + Console.WriteLine( "Thread {0} exiting", + Thread.CurrentThread.GetHashCode() ); + } + + static void Main() { + Thread thread1 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + Thread thread2 = + new Thread( new ThreadStart(EntryPoint.ThreadFunc) ); + + thread1.Start(); + thread2.Start(); + } +} diff --git a/13_canonical_forms/13_clone_1.cs b/13_canonical_forms/13_clone_1.cs new file mode 100644 index 0000000..b688bfc --- /dev/null +++ b/13_canonical_forms/13_clone_1.cs @@ -0,0 +1,17 @@ +using System; + +public sealed class Dimensions : ICloneable +{ + public Dimensions( long width, long height ) { + this.width = width; + this.height = height; + } + + // IClonable implementation + public object Clone() { + return this.MemberwiseClone(); + } + + private long width; + private long height; +} diff --git a/13_canonical_forms/13_clone_2.cs b/13_canonical_forms/13_clone_2.cs new file mode 100644 index 0000000..ea0f138 --- /dev/null +++ b/13_canonical_forms/13_clone_2.cs @@ -0,0 +1,27 @@ +using System; + +public sealed class Dimensions : ICloneable +{ + public Dimensions( long width, long height ) { + Console.WriteLine( "Dimensions( long, long) called" ); + + this.width = width; + this.height = height; + } + + // Private copy constructor used when making a copy of this object. + private Dimensions( Dimensions other ) { + Console.WriteLine( "Dimensions( Dimensions ) called" ); + + this.width = other.width; + this.height = other.height; + } + + // IClonable implementation + public object Clone() { + return new Dimensions(this); + } + + private long width; + private long height; +} diff --git a/13_canonical_forms/13_clone_3.cs b/13_canonical_forms/13_clone_3.cs new file mode 100644 index 0000000..a0082f3 --- /dev/null +++ b/13_canonical_forms/13_clone_3.cs @@ -0,0 +1,63 @@ +using System; + +// Title class +// +public sealed class Title : ICloneable +{ + public enum TitleNameEnum { + GreenHorn, + HotshotGuru + } + + public Title( TitleNameEnum title ) { + this.title = title; + + LookupPayScale(); + } + + private Title( Title other ) { + this.title = other.title; + + LookupPayScale(); + } + + // IClonable implementation + public object Clone() { + return new Title(this); + } + + private void LookupPayScale() { + // Looks up the pay scale in a database. Payscale is + // based upon the title. + } + + private TitleNameEnum title; + private double minPay; + private double maxPay; +} + +// Employee class +// +public sealed class Employee : ICloneable +{ + public Employee( string name, Title title, string ssn ) { + this.name = name; + this.title = title; + this.ssn = ssn; + } + + private Employee( Employee other ) { + this.name = String.Copy( other.name ); + this.title = (Title) other.title.Clone(); + this.ssn = String.Copy( other.ssn ); + } + + // ICloneable implementation + public object Clone() { + return new Employee(this); + } + + private string name; + private Title title; + private string ssn; +} diff --git a/13_canonical_forms/13_clone_4.cs b/13_canonical_forms/13_clone_4.cs new file mode 100644 index 0000000..e69ab6c --- /dev/null +++ b/13_canonical_forms/13_clone_4.cs @@ -0,0 +1,19 @@ +using System; +using CloneHelpers; + +public sealed class Dimensions : ICloneable +{ + public Dimensions( long width, long height ) { + this.width = width; + this.height = height; + } + + // IClonable implementation + [CloneStyleAttribute(CloneStyle.Deep)] + public object Clone() { + return this.MemberwiseClone(); + } + + private long width; + private long height; +} diff --git a/13_canonical_forms/13_clone_attribute.cs b/13_canonical_forms/13_clone_attribute.cs new file mode 100644 index 0000000..64bf03f --- /dev/null +++ b/13_canonical_forms/13_clone_attribute.cs @@ -0,0 +1,27 @@ +using System; + +namespace CloneHelpers +{ + +public enum CloneStyle { + Deep, + Shallow +} + +[AttributeUsageAttribute(AttributeTargets.Method)] +public sealed class CloneStyleAttribute : Attribute +{ + public CloneStyleAttribute( CloneStyle clonestyle ) { + this.clonestyle = clonestyle; + } + + public CloneStyle Style { + get { + return clonestyle; + } + } + + private CloneStyle clonestyle; +} + +} diff --git a/13_canonical_forms/13_comparable_1.cs b/13_canonical_forms/13_comparable_1.cs new file mode 100644 index 0000000..42a058a --- /dev/null +++ b/13_canonical_forms/13_comparable_1.cs @@ -0,0 +1,66 @@ +using System; + +public sealed class ComplexNumber : IComparable +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public override bool Equals( object other ) { + bool result = false; + ComplexNumber that = other as ComplexNumber; + if( that != null ) { + result = InternalEquals( that ); + } + + return result; + } + + public override int GetHashCode() { + return (int) this.Magnitude; + } + + public static bool operator ==( ComplexNumber num1, ComplexNumber num2 ) { + return Object.Equals(num1, num2); + } + + public static bool operator !=( ComplexNumber num1, ComplexNumber num2 ) { + return !Object.Equals(num1, num2); + } + + public int CompareTo( object other ) { + ComplexNumber that = other as ComplexNumber; + if( that == null ) { + throw new ArgumentException( "Bad Comparison!" ); + } + + int result; + if( InternalEquals(that) ) { + result = 0; + } else if( this.Magnitude > that.Magnitude ) { + result = 1; + } else { + result = -1; + } + + return result; + } + + private bool InternalEquals( ComplexNumber that ) { + return (this.real == that.real) && + (this.imaginary == that.imaginary); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} diff --git a/13_canonical_forms/13_const_correct_1.cs b/13_canonical_forms/13_const_correct_1.cs new file mode 100644 index 0000000..0fdff93 --- /dev/null +++ b/13_canonical_forms/13_const_correct_1.cs @@ -0,0 +1,72 @@ +using System; + +public sealed class ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public double Real { + get { + return real; + } + + set { + real = value; + } + } + + public double Imaginary { + get { + return imaginary; + } + + set { + imaginary = value; + } + } + + // Other methods removed for clarity + + private double real; + private double imaginary; +} + +public sealed class ConstComplexNumber +{ + public ConstComplexNumber( ComplexNumber pimpl ) { + this.pimpl = pimpl; + } + + public double Real { + get { + return pimpl.Real; + } + } + + public double Imaginary { + get { + return pimpl.Imaginary; + } + } + + private readonly ComplexNumber pimpl; +} + +public sealed class EntryPoint +{ + static void Main() { + ComplexNumber someNumber = new ComplexNumber( 1, 2 ); + SomeMethod( new ConstComplexNumber(someNumber) ); + + // We are guaranteed by the contract of ConstComplexNumber that + // someNumber has not been changed at this point. + } + + static void SomeMethod( ConstComplexNumber number ) { + Console.WriteLine( "( {0}, {1} )", + number.Real, + number.Imaginary ); + } +} diff --git a/13_canonical_forms/13_convertible_1.cs b/13_canonical_forms/13_convertible_1.cs new file mode 100644 index 0000000..5a38c44 --- /dev/null +++ b/13_canonical_forms/13_convertible_1.cs @@ -0,0 +1,24 @@ +using System; + +public sealed class ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} + +public sealed class EntryPoint +{ + static void Main() { + ComplexNumber num1 = new ComplexNumber( 1.12345678, 2.12345678 ); + + string str = + (string) Convert.ChangeType( num1, typeof(string) ); + } +} diff --git a/13_canonical_forms/13_dispose_1.cs b/13_canonical_forms/13_dispose_1.cs new file mode 100644 index 0000000..6ad862f --- /dev/null +++ b/13_canonical_forms/13_dispose_1.cs @@ -0,0 +1,17 @@ +using System; +using System.IO; + +public sealed class WriteStuff +{ + static void Main(){ + StreamWriter sw = new StreamWriter("Output.txt"); + try { + sw.WriteLine( "This is a test of the emergency dispose mechanism" ); + } + finally { + if( sw != null ) { + ((IDisposable)sw).Dispose(); + } + } + } +} diff --git a/13_canonical_forms/13_dispose_2.cs b/13_canonical_forms/13_dispose_2.cs new file mode 100644 index 0000000..abadd8b --- /dev/null +++ b/13_canonical_forms/13_dispose_2.cs @@ -0,0 +1,11 @@ +using System; +using System.IO; + +public sealed class WriteStuff +{ + static void Main(){ + using( StreamWriter sw = new StreamWriter("Output.txt") ) { + sw.WriteLine( "This is a test of the emergency dispose mechanism" ); + } + } +} diff --git a/13_canonical_forms/13_dispose_3.cs b/13_canonical_forms/13_dispose_3.cs new file mode 100644 index 0000000..6d68a6e --- /dev/null +++ b/13_canonical_forms/13_dispose_3.cs @@ -0,0 +1,28 @@ +using System; +using System.Runtime.InteropServices; + +public sealed class Win32Heap : IDisposable +{ + [DllImport("kernel32.dll")] + static extern IntPtr HeapCreate(uint flOptions, UIntPtr dwInitialSize, + UIntPtr dwMaximumSize); + + [DllImport("kernel32.dll")] + static extern bool HeapDestroy(IntPtr hHeap); + + public Win32Heap() { + theHeap = HeapCreate( 0, (UIntPtr) 4096, UIntPtr.Zero ); + } + + // IDisposable implementation + public void Dispose() { + if( !disposed ) { + HeapDestroy( theHeap ); + theHeap = IntPtr.Zero; + disposed = true; + } + } + + private IntPtr theHeap; + private bool disposed = false; +} diff --git a/13_canonical_forms/13_finalize_1.cs b/13_canonical_forms/13_finalize_1.cs new file mode 100644 index 0000000..3f6b939 --- /dev/null +++ b/13_canonical_forms/13_finalize_1.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.InteropServices; + +public class Win32Heap : IDisposable +{ + [DllImport("kernel32.dll")] + static extern IntPtr HeapCreate(uint flOptions, UIntPtr dwInitialSize, + UIntPtr dwMaximumSize); + + [DllImport("kernel32.dll")] + static extern bool HeapDestroy(IntPtr hHeap); + + public Win32Heap() { + theHeap = HeapCreate( 0, (UIntPtr) 4096, UIntPtr.Zero ); + } + + // IDisposable implementation + protected virtual void Dispose( bool disposing ) { + if( !disposed ) { + if( disposing ) { + // It's ok to use any internal objects here. This class happens + // to not have any though. + } + + // If using objects that you know do still exist, such as objects + // that implement the singleton pattern, it is important to make + // sure those objects are thread safe. + + HeapDestroy( theHeap ); + theHeap = IntPtr.Zero; + disposed = true; + } + } + + public void Dispose() { + Dispose( true ); + GC.SuppressFinalize( this ); + } + + ~Win32Heap() { + Dispose( false ); + } + + private IntPtr theHeap; + private bool disposed = false; +} diff --git a/13_canonical_forms/13_finalize_2.cs b/13_canonical_forms/13_finalize_2.cs new file mode 100644 index 0000000..9d3c3c8 --- /dev/null +++ b/13_canonical_forms/13_finalize_2.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.InteropServices; +using System.Diagnostics; + +public sealed class Win32Heap : IDisposable +{ + [DllImport("kernel32.dll")] + static extern IntPtr HeapCreate(uint flOptions, + UIntPtr dwInitialSize, + UIntPtr dwMaximumSize); + + [DllImport("kernel32.dll")] + static extern bool HeapDestroy(IntPtr hHeap); + + public Win32Heap() { + creationStackTrace = new StackTrace(1, true); + + theHeap = HeapCreate( 0, (UIntPtr) 4096, UIntPtr.Zero ); + } + + // IDisposable implementation + private void Dispose( bool disposing ) { + if( !disposed ) { + if( disposing ) { + // It's ok to use any internal objects here. This + // class happens to not have any though. + } else { + // OOPS! We're finalizing this object and it has not + // been disposed. Let's let the user know about it if + // the app domain is not shutting down. + AppDomain currentDomain = AppDomain.CurrentDomain; + if( !currentDomain.IsFinalizingForUnload() && + !Environment.HasShutdownStarted ) { + Console.WriteLine( + "Failed to dispose of object!!!" ); + Console.WriteLine( "Object allocated at:" ); + for( int i = 0; + i < creationStackTrace.FrameCount; + ++i ) { + StackFrame frame = + creationStackTrace.GetFrame(i); + Console.WriteLine( " {0}", + frame.ToString() ); + } + } + } + + // If using objects that you know do still exist, such + // as objects that implement the singleton pattern, it + // is important to make sure those objects are thread + // safe. + + HeapDestroy( theHeap ); + theHeap = IntPtr.Zero; + disposed = true; + } + } + + public void Dispose() { + Dispose( true ); + GC.SuppressFinalize( this ); + } + + ~Win32Heap() { + Dispose( false ); + } + + private IntPtr theHeap; + private bool disposed = false; + private StackTrace creationStackTrace; +} + +public sealed class EntryPoint +{ + static void Main() + { + Win32Heap heap = new Win32Heap(); + heap = null; + GC.Collect(); + GC.WaitForPendingFinalizers(); + } +} diff --git a/13_canonical_forms/13_formattable_1.cs b/13_canonical_forms/13_formattable_1.cs new file mode 100644 index 0000000..d876bc9 --- /dev/null +++ b/13_canonical_forms/13_formattable_1.cs @@ -0,0 +1,47 @@ +using System; +using System.Globalization; + +public sealed class ComplexNumber : IFormattable +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public override string ToString() { + return ToString( "G", null ); + } + + // IFormattable implementation + public string ToString( string format, + IFormatProvider formatProvider ) { + string result = "(" + + real.ToString(format, formatProvider) + + " " + + real.ToString(format, formatProvider) + + ")"; + return result; + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} + +public sealed class EntryPoint +{ + static void Main() { + ComplexNumber num1 = new ComplexNumber( 1.12345678, + 2.12345678 ); + + Console.WriteLine( "US format: {0}", + num1.ToString( "F5", + new CultureInfo("en-US") ) ); + Console.WriteLine( "DE format: {0}", + num1.ToString( "F5", + new CultureInfo("de-DE") ) ); + Console.WriteLine( "Object.ToString(): {0}", + num1.ToString() ); + } +} diff --git a/13_canonical_forms/13_gethashcode_1.cs b/13_canonical_forms/13_gethashcode_1.cs new file mode 100644 index 0000000..28cee92 --- /dev/null +++ b/13_canonical_forms/13_gethashcode_1.cs @@ -0,0 +1,38 @@ +using System; + +public sealed class ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public override bool Equals( object other ) { + bool result = false; + ComplexNumber that = other as ComplexNumber; + if( that != null ) { + result = (this.real == that.real) && + (this.imaginary == that.imaginary); + } + + return result; + } + + public override int GetHashCode() { + return (int) Math.Sqrt( Math.Pow(this.real, 2) * + Math.Pow(this.imaginary, 2) ); + } + + public static bool operator ==( ComplexNumber num1, ComplexNumber num2 ) { + return Object.Equals(num1, num2); + } + + public static bool operator !=( ComplexNumber num1, ComplexNumber num2 ) { + return !Object.Equals(num1, num2); + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} diff --git a/13_canonical_forms/13_nvi_1.cs b/13_canonical_forms/13_nvi_1.cs new file mode 100644 index 0000000..00148ef --- /dev/null +++ b/13_canonical_forms/13_nvi_1.cs @@ -0,0 +1,23 @@ +using System; + +public class Base +{ + public virtual void DoWork() { + Console.WriteLine( "Base.DoWork()" ); + } +} + +public class Derived : Base +{ + public override void DoWork() { + Console.WriteLine( "Derived.DoWork()" ); + } +} + +public class EntryPoint +{ + static void Main() { + Base b = new Derived(); + b.DoWork(); + } +} diff --git a/13_canonical_forms/13_nvi_2.cs b/13_canonical_forms/13_nvi_2.cs new file mode 100644 index 0000000..0e6834a --- /dev/null +++ b/13_canonical_forms/13_nvi_2.cs @@ -0,0 +1,27 @@ +using System; + +public class Base +{ + public void DoWork() { + CoreDoWork(); + } + + protected virtual void CoreDoWork() { + Console.WriteLine( "Base.DoWork()" ); + } +} + +public class Derived : Base +{ + protected override void CoreDoWork() { + Console.WriteLine( "Derived.DoWork()" ); + } +} + +public class EntryPoint +{ + static void Main() { + Base b = new Derived(); + b.DoWork(); + } +} diff --git a/13_canonical_forms/13_nvi_3.cs b/13_canonical_forms/13_nvi_3.cs new file mode 100644 index 0000000..80f8e48 --- /dev/null +++ b/13_canonical_forms/13_nvi_3.cs @@ -0,0 +1,30 @@ +// WILL NOT COMPILE!!!!! +using System; + +public class Base +{ + public void DoWork() { + CoreDoWork(); + } + + // WILL NOT COMPILE!!!!! + private virtual void CoreDoWork() { + Console.WriteLine( "Base.DoWork()" ); + } +} + +public class Derived : Base +{ + // WILL NOT COMPILE!!!!! + private override void CoreDoWork() { + Console.WriteLine( "Derived.DoWork()" ); + } +} + +public class EntryPoint +{ + static void Main() { + Base b = new Derived(); + b.DoWork(); + } +} diff --git a/13_canonical_forms/13_operators_1.cs b/13_canonical_forms/13_operators_1.cs new file mode 100644 index 0000000..83e4e13 --- /dev/null +++ b/13_canonical_forms/13_operators_1.cs @@ -0,0 +1,37 @@ +sealed public class Point +{ + // other methods removed for clarity + + public override bool Equals( object other ) { + bool result = false; + Point that = other as Point; + if( that != null ) { + result = (this.coordinates == that.coordinates); + } + + return result; + } + + public override int GetHashCode() { + return precomputedHash; + } + + public static bool operator ==( Point pt1, Point pt2 ) { + if( pt1.GetHashCode() != pt2.GetHashCode() ) { + return false; + } else { + return Object.Equals( pt1, pt2 ); + } + } + + public static bool operator !=( Point pt1, Point pt2 ) { + if( pt1.GetHashCode() != pt2.GetHashCode() ) { + return true; + } else { + return !Object.Equals( pt1, pt2 ); + } + } + + private float[] coordinates; + private int precomputedHash; +} diff --git a/13_canonical_forms/13_string_oddity_1.cs b/13_canonical_forms/13_string_oddity_1.cs new file mode 100644 index 0000000..06ec34b --- /dev/null +++ b/13_canonical_forms/13_string_oddity_1.cs @@ -0,0 +1,22 @@ +using System; + +namespace string_test +{ + class Program + { + static void Main(string[] args) { + string strOriginal = "Original String"; + Console.WriteLine( "Value of strOriginal before call: {0}", + strOriginal ); + + TryToAlterString( strOriginal ); + + Console.WriteLine( "Value of strOriginal after call: {0}", + strOriginal ); + } + + static void TryToAlterString(string str) { + str = "Modified String"; + } + } +} diff --git a/13_canonical_forms/13_strong_types_1.cs b/13_canonical_forms/13_strong_types_1.cs new file mode 100644 index 0000000..a610776 --- /dev/null +++ b/13_canonical_forms/13_strong_types_1.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections; + +public class Employee +{ + public void Evaluate() { + Console.WriteLine( "Evaluating Employee..." ); + } +} + +public class WorkForceEnumerator : IEnumerator +{ + public WorkForceEnumerator( ArrayList employees ) { + this.enumerator = employees.GetEnumerator(); + } + + public Employee Current { + get { + return (Employee) enumerator.Current; + } + } + + object IEnumerator.Current { + get { + return enumerator.Current; + } + } + + public bool MoveNext() { + return enumerator.MoveNext(); + } + + public void Reset() { + enumerator.Reset(); + } + + private IEnumerator enumerator; +} + +public class WorkForce : IEnumerable +{ + public WorkForce() { + employees = new ArrayList(); + + // Let's put an employee in here for demo purposes. + employees.Add( new Employee() ); + } + + public WorkForceEnumerator GetEnumerator() { + return new WorkForceEnumerator( employees ); + } + + IEnumerator IEnumerable.GetEnumerator() { + return new WorkForceEnumerator( employees ); + } + + private ArrayList employees; +} + +public class EntryPoint +{ + static void Main() { + WorkForce staff = new WorkForce(); + foreach( Employee emp in staff ) { + emp.Evaluate(); + } + } +} diff --git a/13_canonical_forms/13_strong_types_2.cs b/13_canonical_forms/13_strong_types_2.cs new file mode 100644 index 0000000..f94a2ab --- /dev/null +++ b/13_canonical_forms/13_strong_types_2.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections; + +public class Employee +{ + public void Evaluate() { + Console.WriteLine( "Evaluating Employee..." ); + } +} + +public class WorkForceEnumerator : IEnumerator +{ + public WorkForceEnumerator( ArrayList employees ) { + this.enumerator = employees.GetEnumerator(); + } + + public object Current { + get { + return enumerator.Current; + } + } + + public bool MoveNext() { + return enumerator.MoveNext(); + } + + public void Reset() { + enumerator.Reset(); + } + + private IEnumerator enumerator; +} + +public class WorkForce : IEnumerable +{ + public WorkForce() { + employees = new ArrayList(); + + // Let's put an employee in here for demo purposes. + employees.Add( new Employee() ); + } + + public IEnumerator GetEnumerator() { + return new WorkForceEnumerator( employees ); + } + + private ArrayList employees; +} + +public class EntryPoint +{ + static void Main() { + WorkForce staff = new WorkForce(); + foreach( Employee emp in staff ) { + emp.Evaluate(); + } + } +} diff --git a/13_canonical_forms/13_typesafe_methods_1.cs b/13_canonical_forms/13_typesafe_methods_1.cs new file mode 100644 index 0000000..588d2b6 --- /dev/null +++ b/13_canonical_forms/13_typesafe_methods_1.cs @@ -0,0 +1,88 @@ +using System; + +public struct ComplexNumber : IComparable, + IComparable, + IEquatable +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public bool Equals( ComplexNumber other ) { + return (this.real == other.real) && + (this.imaginary == other.imaginary); + } + + public override bool Equals( object other ) { + bool result = false; + if( other is ComplexNumber ) { + ComplexNumber that = (ComplexNumber) other ; + + result = Equals( that ); + } + + return result; + } + + public override int GetHashCode() { + return (int) this.Magnitude; + } + + public static bool operator ==( ComplexNumber num1, + ComplexNumber num2 ) { + return num1.Equals(num2); + } + + public static bool operator !=( ComplexNumber num1, + ComplexNumber num2 ) { + return !num1.Equals(num2); + } + + public int CompareTo( ComplexNumber that ) { + int result; + if( Equals(that) ) { + result = 0; + } else if( this.Magnitude > that.Magnitude ) { + result = 1; + } else { + result = -1; + } + + return result; + } + + int IComparable.CompareTo( object other ) { + if( !(other is ComplexNumber) ) { + throw new ArgumentException( "Bad Comparison!" ); + } + + return CompareTo( (ComplexNumber) other ); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} + +public sealed class EntryPoint +{ + static void Main() + { + ComplexNumber num1 = new ComplexNumber( 1, 3 ); + ComplexNumber num2 = new ComplexNumber( 1, 2 ); + + int result = num1.CompareTo( num2 ); + + // Now, try the type-generic version + result = ((IComparable)num1).CompareTo( num2 ); + } +} diff --git a/13_canonical_forms/13_value_equals_1.cs b/13_canonical_forms/13_value_equals_1.cs new file mode 100644 index 0000000..efdc4b6 --- /dev/null +++ b/13_canonical_forms/13_value_equals_1.cs @@ -0,0 +1,81 @@ +using System; + +public struct ComplexNumber : IComparable +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public override bool Equals( object other ) { + bool result = false; + if( other is ComplexNumber ) { + ComplexNumber that = (ComplexNumber) other ; + + result = InternalEquals( that ); + } + + return result; + } + + public override int GetHashCode() { + return (int) this.Magnitude; + } + + public static bool operator ==( ComplexNumber num1, + ComplexNumber num2 ) { + return num1.Equals(num2); + } + + public static bool operator !=( ComplexNumber num1, + ComplexNumber num2 ) { + return !num1.Equals(num2); + } + + public int CompareTo( object other ) { + if( !(other is ComplexNumber) ) { + throw new ArgumentException( "Bad Comparison!" ); + } + + ComplexNumber that = (ComplexNumber) other; + + int result; + if( InternalEquals(that) ) { + result = 0; + } else if( this.Magnitude > that.Magnitude ) { + result = 1; + } else { + result = -1; + } + + return result; + } + + private bool InternalEquals( ComplexNumber that ) { + return (this.real == that.real) && + (this.imaginary == that.imaginary); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} + +public sealed class EntryPoint +{ + static void Main() + { + ComplexNumber num1 = new ComplexNumber( 1, 2 ); + ComplexNumber num2 = new ComplexNumber( 1, 2 ); + + bool result = num1.Equals( num2 ); + } +} diff --git a/13_canonical_forms/13_value_equals_2.cs b/13_canonical_forms/13_value_equals_2.cs new file mode 100644 index 0000000..83d01a0 --- /dev/null +++ b/13_canonical_forms/13_value_equals_2.cs @@ -0,0 +1,85 @@ +using System; + +public struct ComplexNumber : IComparable, + IComparable, + IEquatable +{ + public ComplexNumber( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public bool Equals( ComplexNumber other ) { + return (this.real == other.real) && + (this.imaginary == other.imaginary); + } + + public override bool Equals( object other ) { + bool result = false; + if( other is ComplexNumber ) { + ComplexNumber that = (ComplexNumber) other ; + + result = Equals( that ); + } + + return result; + } + + public override int GetHashCode() { + return (int) this.Magnitude; + } + + public static bool operator ==( ComplexNumber num1, + ComplexNumber num2 ) { + return num1.Equals(num2); + } + + public static bool operator !=( ComplexNumber num1, + ComplexNumber num2 ) { + return !num1.Equals(num2); + } + + public int CompareTo( object other ) { + if( !(other is ComplexNumber) ) { + throw new ArgumentException( "Bad Comparison!" ); + } + + return CompareTo( (ComplexNumber) other ); + } + + public int CompareTo( ComplexNumber that ) { + int result; + if( Equals(that) ) { + result = 0; + } else if( this.Magnitude > that.Magnitude ) { + result = 1; + } else { + result = -1; + } + + return result; + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + // Other methods removed for clarity + + private readonly double real; + private readonly double imaginary; +} + +public sealed class EntryPoint +{ + static void Main() + { + ComplexNumber num1 = new ComplexNumber( 1, 2 ); + ComplexNumber num2 = new ComplexNumber( 1, 2 ); + + bool result = num1.Equals( num2 ); + } +} diff --git a/13_canonical_forms/4_equality_1.cs b/13_canonical_forms/4_equality_1.cs new file mode 100644 index 0000000..67f54c7 --- /dev/null +++ b/13_canonical_forms/4_equality_1.cs @@ -0,0 +1,16 @@ +public class EntryPoint +{ + static bool TestForEquality( object obj1, object obj2 ) + { + return obj1.Equals( obj2 ); + } + + static void Main() + { + object obj1 = new System.Object(); + object obj2 = null; + + System.Console.WriteLine( "obj1 == obj2 is {0}", + TestForEquality(obj1, obj2) ); + } +} diff --git a/13_canonical_forms/4_equality_3.cs b/13_canonical_forms/4_equality_3.cs new file mode 100644 index 0000000..23a026c --- /dev/null +++ b/13_canonical_forms/4_equality_3.cs @@ -0,0 +1,27 @@ +public class EntryPoint +{ + static bool TestForEquality( object obj1, object obj2 ) + { + if( obj1 == null && obj2 == null ) { + return true; + } + + if( obj1 == null ) + { + return false; + } + + return obj1.Equals( obj2 ); + } + + static void Main() + { + object obj1 = new System.Object(); + object obj2 = null; + + System.Console.WriteLine( "obj1 == obj2 is {0}", + TestForEquality(obj2, obj1) ); + System.Console.WriteLine( "null == null is {0}", + TestForEquality(null, null) ); + } +} diff --git a/13_canonical_forms/4_ref_type_equals_1.cs b/13_canonical_forms/4_ref_type_equals_1.cs new file mode 100644 index 0000000..30481bd --- /dev/null +++ b/13_canonical_forms/4_ref_type_equals_1.cs @@ -0,0 +1,57 @@ +public class ComplexNumber +{ + public ComplexNumber( int real, int imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + public override bool Equals( object obj ) + { + ComplexNumber other = obj as ComplexNumber; + + if( other == null ) + { + return false; + } + + return (this.real == other.real) && + (this.imaginary == other.imaginary); + } + + public override int GetHashCode() + { + return (int) real ^ (int) imaginary; + } + + public static bool operator==( ComplexNumber me, ComplexNumber other ) + { + return Equals( me, other ); + } + + public static bool operator!=( ComplexNumber me, ComplexNumber other ) + { + return Equals( me, other ); + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() + { + ComplexNumber referenceA = new ComplexNumber( 1, 2 ); + ComplexNumber referenceB = new ComplexNumber( 1, 2 ); + + System.Console.WriteLine( "Result of Equality is {0}", + referenceA == referenceB ); + + // If we really want referential equality. + System.Console.WriteLine( "Identity of references is {0}", + (object) referenceA == (object) referenceB ); + System.Console.WriteLine( "Identity of references is {0}", + ReferenceEquals(referenceA, referenceB) ); + } +} diff --git a/13_canonical_forms/4_references_1.cs b/13_canonical_forms/4_references_1.cs new file mode 100644 index 0000000..3f71145 --- /dev/null +++ b/13_canonical_forms/4_references_1.cs @@ -0,0 +1,8 @@ +public class EntryPoint +{ + static void Main() + { + object referenceA = new System.Object(); + object referenceB = referenceA; + } +} diff --git a/13_canonical_forms/4_references_2.cs b/13_canonical_forms/4_references_2.cs new file mode 100644 index 0000000..253292d --- /dev/null +++ b/13_canonical_forms/4_references_2.cs @@ -0,0 +1,23 @@ +public class ComplexNumber +{ + public ComplexNumber( int real, int imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + private int real; + private int imaginary; +} + +public class EntryPoint +{ + static void Main() + { + ComplexNumber referenceA = new ComplexNumber( 1, 2 ); + ComplexNumber referenceB = new ComplexNumber( 1, 2 ); + + System.Console.WriteLine( "Result of Equality is {0}", + referenceA == referenceB ); + } +} diff --git a/14_extension_methods/custom_iterator_1.cs b/14_extension_methods/custom_iterator_1.cs new file mode 100644 index 0000000..c54369e --- /dev/null +++ b/14_extension_methods/custom_iterator_1.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; + +public class IteratorExample +{ + static void Main() { + var matrix = new List> { + new List { 1, 2, 3 }, + new List { 4, 5, 6 }, + new List { 7, 8, 9 } + }; + + // One way of iterating the matrix. + foreach( var list in matrix ) { + foreach( var item in list ) { + Console.Write( "{0}, ", item ); + } + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/custom_iterator_2.cs b/14_extension_methods/custom_iterator_2.cs new file mode 100644 index 0000000..4e919f2 --- /dev/null +++ b/14_extension_methods/custom_iterator_2.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; + +public static class CustomIterators +{ + public static IEnumerable GetRowMajorIterator( + this List> matrix ) { + foreach( var row in matrix ) { + foreach( var item in row ) { + yield return item; + } + } + } +} + +public class IteratorExample +{ + static void Main() { + var matrix = new List> { + new List { 1, 2, 3 }, + new List { 4, 5, 6 }, + new List { 7, 8, 9 } + }; + + // A more elegant way to enumerate the items. + foreach( var item in matrix.GetRowMajorIterator() ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/custom_iterator_3.cs b/14_extension_methods/custom_iterator_3.cs new file mode 100644 index 0000000..3fcc742 --- /dev/null +++ b/14_extension_methods/custom_iterator_3.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, CreateList(iter) ); + } + + private MyList( T head, IList tail ) { + this.head = head; + this.tail = tail; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + return tail; + } + } + + private T head; + private IList tail; +} + +public static class CustomIterators +{ + public static IEnumerable + LinkListIterator( this IList theList ) { + + for( var list = theList; + list.Tail != null; + list = list.Tail ) { + yield return list.Head; + } + } +} + +public class IteratorExample +{ + static void Main() { + var listInts = new List { 1, 2, 3, 4 }; + var linkList = + MyList.CreateList( listInts ); + + foreach( var item in linkList.LinkListIterator() ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/custom_iterator_4.cs b/14_extension_methods/custom_iterator_4.cs new file mode 100644 index 0000000..2026cf4 --- /dev/null +++ b/14_extension_methods/custom_iterator_4.cs @@ -0,0 +1,79 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, CreateList(iter) ); + } + + private MyList( T head, IList tail ) { + this.head = head; + this.tail = tail; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + return tail; + } + } + + private T head; + private IList tail; +} + +public static class CustomIterators +{ + public static IEnumerable + GeneralIterator( this IList theList, + Func, bool> finalState, + Func, IList> incrementer ) { + while( !finalState(theList) ) { + yield return theList.Head; + theList = incrementer( theList ); + } + } +} + +public class IteratorExample +{ + static void Main() { + var listInts = new List { 1, 2, 3, 4 }; + var linkList = + MyList.CreateList( listInts ); + + var iterator = linkList.GeneralIterator( delegate( IList list ) { + return list.Tail == null; + }, + delegate( IList list ) { + return list.Tail; + } ); + foreach( var item in iterator ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/custom_iterator_5.cs b/14_extension_methods/custom_iterator_5.cs new file mode 100644 index 0000000..d086a2a --- /dev/null +++ b/14_extension_methods/custom_iterator_5.cs @@ -0,0 +1,96 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, CreateList(iter) ); + } + + private MyList( T head, IList tail ) { + this.head = head; + this.tail = tail; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + return tail; + } + } + + private T head; + private IList tail; +} + +public static class CustomIterators +{ + public static IEnumerable + GeneralIterator( this IList theList, + Func, bool> finalState, + Func, IList> incrementer ) { + while( !finalState(theList) ) { + yield return theList.Head; + theList = incrementer( theList ); + } + } + + public static IList Reverse( this IList theList ) { + var reverseList = new List(); + Func, List> reverseFunc = null; + + reverseFunc = delegate(IList list) { + if( list != null ) { + reverseFunc( list.Tail ); + if( list.Tail != null ) { + reverseList.Add( list.Head ); + } + } + return reverseList; + }; + + return MyList.CreateList( reverseFunc(theList) ); + } +} + +public class IteratorExample +{ + static void Main() { + var listInts = new List { 1, 2, 3, 4 }; + var linkList = + MyList.CreateList( listInts ); + + var iterator = linkList.Reverse().GeneralIterator( delegate( IList list ) { + return list.Tail == null; + }, + delegate( IList list ) { + return list.Tail; + } ); + foreach( var item in iterator ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/custom_iterator_6.cs b/14_extension_methods/custom_iterator_6.cs new file mode 100644 index 0000000..2534ef2 --- /dev/null +++ b/14_extension_methods/custom_iterator_6.cs @@ -0,0 +1,95 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, CreateList(iter) ); + } + + public MyList( T head, IList tail ) { + this.head = head; + this.tail = tail; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + return tail; + } + } + + private T head; + private IList tail; +} + +public static class CustomIterators +{ + public static IEnumerable + GeneralIterator( this IList theList, + Func, bool> finalState, + Func, IList> incrementer ) { + while( !finalState(theList) ) { + yield return theList.Head; + theList = incrementer( theList ); + } + } + + public static IList Reverse( this IList theList ) { + var reverseList = new MyList(default(T), null); + Func, MyList> reverseFunc = null; + + reverseFunc = delegate(IList list) { + if( list.Tail != null ) { + reverseList = new MyList( list.Head, reverseList ); + reverseFunc( list.Tail ); + } + + return reverseList; + }; + + return reverseFunc(theList); + } +} + +public class IteratorExample +{ + static void Main() { + var listInts = new List { 1, 2, 3, 4 }; + var linkList = + MyList.CreateList( listInts ); + + var iterator = linkList.Reverse().GeneralIterator( delegate( IList list ) { + return list.Tail == null; + }, + delegate( IList list ) { + return list.Tail; + } ); + foreach( var item in iterator ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/custom_iterator_7.cs b/14_extension_methods/custom_iterator_7.cs new file mode 100644 index 0000000..28cca29 --- /dev/null +++ b/14_extension_methods/custom_iterator_7.cs @@ -0,0 +1,93 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, CreateList(iter) ); + } + + public MyList( T head, IList tail ) { + this.head = head; + this.tail = tail; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + return tail; + } + } + + private T head; + private IList tail; +} + +public static class CustomIterators +{ + public static IEnumerable + GeneralIterator( this IList theList, + Func, bool> finalState, + Func, IList> incrementer ) { + while( !finalState(theList) ) { + yield return theList.Head; + theList = incrementer( theList ); + } + } + + public static IList Reverse( this IList theList ) { + Func, IList, IList> reverseFunc = null; + + reverseFunc = delegate(IList list, IList result) { + if( list.Tail != null ) { + return reverseFunc( list.Tail, new MyList(list.Head, result) ); + } + + return result; + }; + + return reverseFunc(theList, new MyList(default(T), null)); + } +} + +public class IteratorExample +{ + static void Main() { + var listInts = new List { 1, 2, 3, 4 }; + var linkList = + MyList.CreateList( listInts ); + + var iterator = linkList.Reverse().GeneralIterator( delegate( IList list ) { + return list.Tail == null; + }, + delegate( IList list ) { + return list.Tail; + } ); + foreach( var item in iterator ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/14_extension_methods/ext_method_intro_1.cs b/14_extension_methods/ext_method_intro_1.cs new file mode 100644 index 0000000..3daf302 --- /dev/null +++ b/14_extension_methods/ext_method_intro_1.cs @@ -0,0 +1,26 @@ +using System; + +namespace ExtensionMethodDemo +{ + +public static class ExtensionMethods +{ + public static void SendToLog( this String str ) { + Console.WriteLine( str ); + } +} + +public class ExtensionMethodIntro +{ + static void Main() { + String str = "Some useful information to log"; + + // Call the extension method + str.SendToLog(); + + // Call the same method the old way. + ExtensionMethods.SendToLog( str ); + } +} + +} diff --git a/14_extension_methods/ext_method_lookup_1.cs b/14_extension_methods/ext_method_lookup_1.cs new file mode 100644 index 0000000..406d238 --- /dev/null +++ b/14_extension_methods/ext_method_lookup_1.cs @@ -0,0 +1,102 @@ +using System; + +public static class ExtensionMethods +{ + static public void WriteLine( this String str ) { + Console.WriteLine( "Default Namespace: " + str ); + } +} + +namespace A +{ + public static class ExtensionMethods + { + static public void WriteLine( this String str ) { + Console.WriteLine( "Namespace A: " + str ); + } + } +} + +namespace B +{ + public static class ExtensionMethods + { + static public void WriteLine( this String str ) { + Console.WriteLine( "Namespace B: " + str ); + } + } +} + +namespace C +{ + using A; + + public class Employee + { + public Employee( String name ) { + this.name = name; + } + + public void PrintName() { + name.WriteLine(); + } + + private String name; + } +} + +namespace D +{ + using B; + + public class Dog + { + public Dog( String name ) { + this.name = name; + } + + public void PrintName() { + name.WriteLine(); + } + + private String name; + } +} + +namespace E +{ + public class Cat + { + public Cat( String name ) { + this.name = name; + } + + public void PrintName() { + name.WriteLine(); + } + + private String name; + } +} + +namespace Demo +{ + using A; + using B; + + public class EntryPoint + { + static void Main() { + C.Employee fred = new C.Employee( "Fred" ); + D.Dog thor = new D.Dog( "Thor" ); + E.Cat sylvester = new E.Cat( "Sylvester" ); + + fred.PrintName(); + thor.PrintName(); + sylvester.PrintName(); + + // String str = "Etouffe"; + // str.WriteLine(); + } + } +} diff --git a/14_extension_methods/transform_1.cs b/14_extension_methods/transform_1.cs new file mode 100644 index 0000000..57c8d95 --- /dev/null +++ b/14_extension_methods/transform_1.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; + +public class TransformExample +{ + static void Main() { + var intList = new List() { 1, 2, 3, 4, 5 }; + + var doubleList = new List(); + + // Compute the new list. + foreach( var item in intList ) { + doubleList.Add( (double) item / 3 ); + Console.WriteLine( item ); + } + Console.WriteLine(); + + // Display the new list. + foreach( var item in doubleList ) { + Console.WriteLine( item ); + } + Console.WriteLine(); + } +} diff --git a/14_extension_methods/transform_2.cs b/14_extension_methods/transform_2.cs new file mode 100644 index 0000000..a019adc --- /dev/null +++ b/14_extension_methods/transform_2.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; + +public class TransformExample +{ + delegate double Operation( int item ); + + static List Transform( List input, Operation op ) { + List result = new List(); + foreach( var item in input ) { + result.Add( op(item) ); + } + + return result; + } + + static double DivideByThree( int n ) { + return (double)n / 3; + } + + static void Main() { + var intList = new List() { 1, 2, 3, 4, 5 }; + + // Compute the new list. + var doubleList = Transform( intList, DivideByThree ); + + foreach( var item in intList ) { + Console.WriteLine( item ); + } + Console.WriteLine(); + + // Display the new list. + foreach( var item in doubleList ) { + Console.WriteLine( item ); + } + Console.WriteLine(); + } +} diff --git a/14_extension_methods/transform_3.cs b/14_extension_methods/transform_3.cs new file mode 100644 index 0000000..378ef96 --- /dev/null +++ b/14_extension_methods/transform_3.cs @@ -0,0 +1,39 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class MyExtensions +{ + public static IEnumerable Transform( + this IEnumerable input, + Func op ) { + foreach( var item in input ) { + yield return op( item ); + } + } +} + +public class TransformExample +{ + static double DivideByThree( int n ) { + return (double)n / 3; + } + + static void Main() { + var intList = new List() { 1, 2, 3, 4, 5 }; + + // Compute the new list. + var doubleList = + intList.Transform( new Func(DivideByThree) ); + + foreach( var item in intList ) { + Console.WriteLine( item ); + } + Console.WriteLine(); + + // Display the new list. + foreach( var item in doubleList ) { + Console.WriteLine( item ); + } + } +} diff --git a/14_extension_methods/transform_4.cs b/14_extension_methods/transform_4.cs new file mode 100644 index 0000000..dcf2700 --- /dev/null +++ b/14_extension_methods/transform_4.cs @@ -0,0 +1,39 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class MyExtensions +{ + public static IEnumerable Transform( + this IEnumerable input, + Func op ) { + foreach( var item in input ) { + yield return op( item ); + } + } +} + +public class TransformExample +{ + static IEnumerable CreateInfiniteSeries() { + int n = 0; + while( true ) { + yield return n++; + } + } + + static void Main() { + var infiniteSeries1 = CreateInfiniteSeries(); + + var infiniteSeries2 = + infiniteSeries1.Transform( x => (double)x / 3 ); + + IEnumerator iter = + infiniteSeries2.GetEnumerator(); + + for( int i = 0; i < 25; ++i ) { + iter.MoveNext(); + Console.WriteLine( iter.Current ); + } + } +} diff --git a/14_extension_methods/transform_chain_1.cs b/14_extension_methods/transform_chain_1.cs new file mode 100644 index 0000000..4de8664 --- /dev/null +++ b/14_extension_methods/transform_chain_1.cs @@ -0,0 +1,47 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class MyExtensions +{ + public static IEnumerable Transform( + this IEnumerable input, + Func op ) { + foreach( var item in input ) { + yield return op( item ); + } + } +} + +public class TransformExample +{ + static IEnumerable CreateInfiniteList() { + int n = 0; + while( true ) yield return n++; + } + + static double DivideByThree( int n ) { + return (double)n / 3; + } + + static double Square( double r ) { + return r * r; + } + + static void Main() { + var divideByThree = + new Func( DivideByThree ); + var squareNumber = + new Func( Square ); + + var result = CreateInfiniteList(). + Transform( divideByThree ). + Transform( squareNumber ); + + var iter = result.GetEnumerator(); + for( int i = 0; i < 25; ++i ) { + iter.MoveNext(); + Console.WriteLine( iter.Current ); + } + } +} diff --git a/14_extension_methods/visitor_1.cs b/14_extension_methods/visitor_1.cs new file mode 100644 index 0000000..633ed37 --- /dev/null +++ b/14_extension_methods/visitor_1.cs @@ -0,0 +1,51 @@ +using System; +using ValidatorExtensions; + +namespace ValidatorExtensions +{ + public static class Validators + { + public static void Validate( this String str ) { + // Do something to validate the String instance. + + Console.WriteLine( "String with \"" + + str + + "\" Validated." ); + } + + public static void Validate( this SupplyCabinet cab ) { + // Do something to validate the SupplyCabinet instance. + + Console.WriteLine( "Supply Cabinet Validated." ); + } + + public static void Validate( this Employee emp ) { + // Do something to validate the Employee instance. + + Console.WriteLine( "** Employee Failed Validation! **" ); + } + } +} + +public class SupplyCabinet +{ +} + +public class Employee +{ +} + +public class MyApplication +{ + static void Main() { + String data = "some important data"; + + SupplyCabinet supplies = new SupplyCabinet(); + + Employee hrLady = new Employee(); + + data.Validate(); + supplies.Validate(); + hrLady.Validate(); + } +} diff --git a/14_extension_methods/visitor_2.cs b/14_extension_methods/visitor_2.cs new file mode 100644 index 0000000..d457a25 --- /dev/null +++ b/14_extension_methods/visitor_2.cs @@ -0,0 +1,61 @@ +using System; +using ValidatorExtensions; + +namespace ValidatorExtensions +{ + public static class Validators + { + public static void Validate( this String str ) { + // Do something to validate the String instance. + + Console.WriteLine( "String with \"" + + str + + "\" Validated." ); + } + + public static void Validate( this Employee emp ) { + // Do something to validate the Employee instance. + + Console.WriteLine( "** Employee Failed Validation! **" ); + } + + public static void Validate( this T obj ) + where T: IValidator { + obj.DoValidation(); + Console.WriteLine( "Instance of following type" + + " validated: " + + obj.GetType() ); + } + } +} + +public interface IValidator +{ + void DoValidation(); +} + +public class SupplyCabinet : IValidator +{ + public void DoValidation() { + Console.WriteLine( "\tValidating SupplyCabinet" ); + } +} + +public class Employee +{ +} + +public class MyApplication +{ + static void Main() { + String data = "some important data"; + + SupplyCabinet supplies = new SupplyCabinet(); + + Employee hrLady = new Employee(); + + data.Validate(); + supplies.Validate(); + hrLady.Validate(); + } +} diff --git a/14_extension_methods/visitor_3.cs b/14_extension_methods/visitor_3.cs new file mode 100644 index 0000000..634feaa --- /dev/null +++ b/14_extension_methods/visitor_3.cs @@ -0,0 +1,70 @@ +using System; +using ValidatorExtensions; + +namespace ValidatorExtensions +{ + public static class Validators + { + public static void Validate( this String str ) { + // Do something to validate the String instance. + + Console.WriteLine( "String with \"" + + str + + "\" Validated." ); + } + + public static void Validate( this SupplyCabinet cab ) { + // Do something to validate the SupplyCabinet instance. + + Console.WriteLine( "Supply Cabinet Validated." ); + } + + public static void Validate( this Employee emp ) { + // Do something to validate the Employee instance. + + Console.WriteLine( "** Employee Failed Validation! **" ); + } + + public static void Validate( this T obj ) + where T: IValidator { + obj.DoValidation(); + Console.WriteLine( "Instance of following type" + + " validated: " + + obj.GetType() ); + } + } +} + +public interface IValidator +{ + void DoValidation(); +} + +public class SupplyCabinet : IValidator +{ + public void DoValidation() { + Console.WriteLine( "\tValidating SupplyCabinet" ); + } +} + +public class Employee +{ +} + +public class MyApplication +{ + static void Main() { + String data = "some important data"; + + SupplyCabinet supplies = new SupplyCabinet(); + + Employee hrLady = new Employee(); + + data.Validate(); + + // Force generic version + supplies.Validate(); + + hrLady.Validate(); + } +} diff --git a/15_lambda_expressions/closure_1.cs b/15_lambda_expressions/closure_1.cs new file mode 100644 index 0000000..45a1f8b --- /dev/null +++ b/15_lambda_expressions/closure_1.cs @@ -0,0 +1,16 @@ +using System; +using System.Linq; + +public class Closures +{ + static void Main() { + int delta = 1; + Func func = (x) => x + delta; + + int currentVal = 0; + for( int i = 0; i < 10; ++i ) { + currentVal = func( currentVal ); + Console.WriteLine( currentVal ); + } + } +} diff --git a/15_lambda_expressions/compound_lambda_1.cs b/15_lambda_expressions/compound_lambda_1.cs new file mode 100644 index 0000000..fcd167d --- /dev/null +++ b/15_lambda_expressions/compound_lambda_1.cs @@ -0,0 +1,17 @@ +using System; +using System.Linq; + +public class Compound +{ + static Func Chain( Func func1, + Func func2 ) { + return x => func2( func1(x) ); + } + + static void Main() { + Func func = Chain( (int x) => x * 3, + (int x) => x + 3.1415 ); + + Console.WriteLine( func(2) ); + } +} diff --git a/15_lambda_expressions/currying_1.cs b/15_lambda_expressions/currying_1.cs new file mode 100644 index 0000000..e80029a --- /dev/null +++ b/15_lambda_expressions/currying_1.cs @@ -0,0 +1,37 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class CurryExtensions +{ + public static Func + Bind2nd( + this Func func, + TArg2 constant ) { + return (x) => func( x, constant ); + } +} + +public class BinderExample +{ + static void Main() { + var mylist = new List { 1.0, 3.4, 5.4, 6.54 }; + var newlist = new List(); + + // Here is the original expression. + Func func = (x, y) => x + y; + + // Here is the curried function. + var funcBound = func.Bind2nd( 3.2 ); + + foreach( var item in mylist ) { + Console.Write( "{0}, ", item ); + newlist.Add( funcBound(item) ); + } + + Console.WriteLine(); + foreach( var item in newlist ) { + Console.Write( "{0}, ", item ); + } + } +} diff --git a/15_lambda_expressions/currying_2.cs b/15_lambda_expressions/currying_2.cs new file mode 100644 index 0000000..e371f4a --- /dev/null +++ b/15_lambda_expressions/currying_2.cs @@ -0,0 +1,36 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class CurryExtensions +{ + public static Func> + Bind2nd( + this Func func ) { + return (y) => (x) => func( x, y ); + } +} + +public class BinderExample +{ + static void Main() { + var mylist = new List { 1.0, 3.4, 5.4, 6.54 }; + var newlist = new List(); + + // Here is the original expression. + Func func = (x, y) => x + y; + + // Here is the curried function. + var funcBound = func.Bind2nd()(3.2); + + foreach( var item in mylist ) { + Console.Write( "{0}, ", item ); + newlist.Add( funcBound(item) ); + } + + Console.WriteLine(); + foreach( var item in newlist ) { + Console.Write( "{0}, ", item ); + } + } +} diff --git a/15_lambda_expressions/custom_iterators_1a.cs b/15_lambda_expressions/custom_iterators_1a.cs new file mode 100644 index 0000000..2a75bab --- /dev/null +++ b/15_lambda_expressions/custom_iterators_1a.cs @@ -0,0 +1,41 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class IteratorExtensions +{ + public static IEnumerable + MakeCustomIterator( + this TCollection collection, + TCursor cursor, + Func getCurrent, + Func isFinished, + Func advanceCursor) { + while( !isFinished(cursor) ) { + yield return getCurrent( collection, cursor ); + cursor = advanceCursor( cursor ); + } + } +} + +public class IteratorExample +{ + static void Main() { + var matrix = new List> { + new List { 1.0, 1.1, 1.2 }, + new List { 2.0, 2.1, 2.2 }, + new List { 3.0, 3.1, 3.2 } + }; + + var iter = matrix.MakeCustomIterator( + new int[] { 0, 0 }, + (coll, cur) => coll[cur[0]][cur[1]], + (cur) => cur[0] > 2 || cur[1] > 2, + (cur) => new int[] { cur[0] + 1, + cur[1] + 1 } ); + + foreach( var item in iter ) { + Console.WriteLine( item ); + } + } +} diff --git a/15_lambda_expressions/custom_iterators_2.cs b/15_lambda_expressions/custom_iterators_2.cs new file mode 100644 index 0000000..6d903bd --- /dev/null +++ b/15_lambda_expressions/custom_iterators_2.cs @@ -0,0 +1,26 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class IteratorExample +{ + static IEnumerable MakeGenerator( T initialValue, + Func advance ) { + T currentValue = initialValue; + while( true ) { + yield return currentValue; + currentValue = advance( currentValue ); + } + } + + static void Main() { + var iter = MakeGenerator( 1, + x => x * 1.2 ); + + var enumerator = iter.GetEnumerator(); + for( int i = 0; i < 10; ++i ) { + enumerator.MoveNext(); + Console.WriteLine( enumerator.Current ); + } + } +} diff --git a/15_lambda_expressions/expression_tree_1.cs b/15_lambda_expressions/expression_tree_1.cs new file mode 100644 index 0000000..ae51547 --- /dev/null +++ b/15_lambda_expressions/expression_tree_1.cs @@ -0,0 +1,17 @@ +using System; +using System.Linq; +using System.Linq.Expressions; + +public class EntryPoint +{ + static void Main() { + Expression> expr = n => n+1; + + Func func = expr.Compile(); + + for( int i = 0; i < 10; ++i ) { + Console.WriteLine( func(i) ); + } + + } +} diff --git a/15_lambda_expressions/expression_tree_2.cs b/15_lambda_expressions/expression_tree_2.cs new file mode 100644 index 0000000..fb702aa --- /dev/null +++ b/15_lambda_expressions/expression_tree_2.cs @@ -0,0 +1,20 @@ +using System; +using System.Linq; +using System.Linq.Expressions; + +public class EntryPoint +{ + static void Main() { + var n = Expression.Parameter( typeof(int), "n" ); + var expr = Expression>.Lambda>( + Expression.Add(n, Expression.Constant(1)), + n ); + + Func func = expr.Compile(); + + for( int i = 0; i < 10; ++i ) { + Console.WriteLine( func(i) ); + } + + } +} diff --git a/15_lambda_expressions/expression_tree_3.cs b/15_lambda_expressions/expression_tree_3.cs new file mode 100644 index 0000000..0e8ba8b --- /dev/null +++ b/15_lambda_expressions/expression_tree_3.cs @@ -0,0 +1,24 @@ +using System; +using System.Linq; +using System.Linq.Expressions; + +public class EntryPoint +{ + static void Main() { + Expression> expr = n => n+1; + + // Now, reassign the expr by multiplying the original + // expression by 2. + expr = Expression>.Lambda>( + Expression.Multiply( expr.Body, + Expression.Constant(2) ), + expr.Parameters ); + + Func func = expr.Compile(); + + for( int i = 0; i < 10; ++i ) { + Console.WriteLine( func(i) ); + } + + } +} diff --git a/15_lambda_expressions/lambda_expression_1.cs b/15_lambda_expressions/lambda_expression_1.cs new file mode 100644 index 0000000..c6f5e45 --- /dev/null +++ b/15_lambda_expressions/lambda_expression_1.cs @@ -0,0 +1,12 @@ +using System; +using System.Linq; + +public class LambdaTest +{ + static void Main() { + Func expr = x => x / 2; + + int someNumber = 9; + Console.WriteLine( "Result: {0}", expr(someNumber) ); + } +} diff --git a/15_lambda_expressions/lambda_expression_2.cs b/15_lambda_expressions/lambda_expression_2.cs new file mode 100644 index 0000000..99dcac4 --- /dev/null +++ b/15_lambda_expressions/lambda_expression_2.cs @@ -0,0 +1,12 @@ +using System; +using System.Linq; + +public class LambdaTest +{ + static void Main() { + Func expr = (double x) => x / 2; + + int someNumber = 9; + Console.WriteLine( "Result: {0}", expr(someNumber) ); + } +} diff --git a/15_lambda_expressions/lambda_expression_3.cs b/15_lambda_expressions/lambda_expression_3.cs new file mode 100644 index 0000000..564b4ed --- /dev/null +++ b/15_lambda_expressions/lambda_expression_3.cs @@ -0,0 +1,21 @@ +using System; +using System.Linq; + +public class LambdaTest +{ + static void Main() { + int counter = 0; + + WriteStream( () => counter++ ); + + Console.WriteLine( "Final value of counter: {0}", + counter ); + } + + static void WriteStream( Func counter ) { + for( int i = 0; i < 10; ++i ) { + Console.Write( "{0}, ", counter() ); + } + Console.WriteLine(); + } +} diff --git a/15_lambda_expressions/lambda_expression_3a.cs b/15_lambda_expressions/lambda_expression_3a.cs new file mode 100644 index 0000000..17e4aa0 --- /dev/null +++ b/15_lambda_expressions/lambda_expression_3a.cs @@ -0,0 +1,41 @@ +using System; + +unsafe public class MyClosure +{ + public MyClosure( int* counter ) + { + this.counter = counter; + } + + public delegate int IncDelegate(); + public IncDelegate GetDelegate() { + return new IncDelegate( IncrementFunction ); + } + + private int IncrementFunction() { + return (*counter)++; + } + + private int* counter; +} + +public class LambdaTest +{ + unsafe static void Main() { + int counter = 0; + + MyClosure closure = new MyClosure( &counter ); + + WriteStream( closure.GetDelegate() ); + + Console.WriteLine( "Final value of counter: {0}", + counter ); + } + + static void WriteStream( MyClosure.IncDelegate incrementor ) { + for( int i = 0; i < 10; ++i ) { + Console.Write( "{0}, ", incrementor() ); + } + Console.WriteLine(); + } +} diff --git a/15_lambda_expressions/lambda_expression_3b.cs b/15_lambda_expressions/lambda_expression_3b.cs new file mode 100644 index 0000000..ff6de7c --- /dev/null +++ b/15_lambda_expressions/lambda_expression_3b.cs @@ -0,0 +1,22 @@ +using System; + +public class LambdaTest +{ + static void Main() { + int counter = 0; + + WriteStream( delegate () { + return counter++; + } ); + + Console.WriteLine( "Final value of counter: {0}", + counter ); + } + + static void WriteStream( Func counter ) { + for( int i = 0; i < 10; ++i ) { + Console.Write( "{0}, ", counter() ); + } + Console.WriteLine(); + } +} diff --git a/15_lambda_expressions/lambda_expression_4.cs b/15_lambda_expressions/lambda_expression_4.cs new file mode 100644 index 0000000..d07f08b --- /dev/null +++ b/15_lambda_expressions/lambda_expression_4.cs @@ -0,0 +1,30 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class LambdaTest +{ + static void Main() { + var teamMembers = new List { + "Lou Loomis", + "Smoke Porterhouse", + "Danny Noonan", + "Ty Webb" + }; + + FindByFirstName( teamMembers, + "Danny", + (x, y) => x.Contains(y) ); + } + + static void FindByFirstName( + List members, + string firstName, + Func predicate ) { + foreach( var member in members ) { + if( predicate(member, firstName) ) { + Console.WriteLine( member ); + } + } + } +} diff --git a/15_lambda_expressions/memoization_1.cs b/15_lambda_expressions/memoization_1.cs new file mode 100644 index 0000000..81893ce --- /dev/null +++ b/15_lambda_expressions/memoization_1.cs @@ -0,0 +1,14 @@ +using System; +using System.Linq; + +public class Proof +{ + static void Main() { + Func fib = null; + fib = (x) => x > 1 ? fib(x-1) + fib(x-2) : x; + + for( int i = 30; i < 40; ++i ) { + Console.WriteLine( fib(i) ); + } + } +} diff --git a/15_lambda_expressions/memoization_2.cs b/15_lambda_expressions/memoization_2.cs new file mode 100644 index 0000000..29c0007 --- /dev/null +++ b/15_lambda_expressions/memoization_2.cs @@ -0,0 +1,33 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class Memoizers +{ + public static Func Memoize( this Func func ) { + var cache = new Dictionary(); + return (x) => { + R result = default(R); + if( cache.TryGetValue(x, out result) ) { + return result; + } + + result = func(x); + cache[x] = result; + return result; + }; + } +} + +public class Proof +{ + static void Main() { + Func fib = null; + fib = (x) => x > 1 ? fib(x-1) + fib(x-2) : x; + fib = fib.Memoize(); + + for( int i = 30; i < 40; ++i ) { + Console.WriteLine( fib(i) ); + } + } +} diff --git a/15_lambda_expressions/memoization_3.cs b/15_lambda_expressions/memoization_3.cs new file mode 100644 index 0000000..5ab052a --- /dev/null +++ b/15_lambda_expressions/memoization_3.cs @@ -0,0 +1,53 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class Memoizers +{ + public static Func Memoize( this Func func ) { + var cache = new Dictionary(); + return (x) => { + R result = default(R); + if( cache.TryGetValue(x, out result) ) { + return result; + } + + result = func(x); + cache[x] = result; + return result; + }; + } +} + +public class Proof +{ + static void Main() { + Func fib = null; + fib = (x) => x > 1 ? fib(x-1) + fib(x-2) : x; + fib = fib.Memoize(); + + Func fibConstant = null; + fibConstant = (x) => { + if( x == 1 ) { + return 1 / ((decimal)fib(x)); + } else { + return 1 / ((decimal)fib(x)) + fibConstant(x-1); + } + }; + fibConstant = fibConstant.Memoize(); + + Console.WriteLine( "\n{0}\t{1}\t{2}\t{3}\n", + "Count", + "Fibonacci".PadRight(24), + "1/Fibonacci".PadRight(24), + "Fibonacci Constant".PadRight(24) ); + + for( ulong i = 1; i <= 93; ++i ) { + Console.WriteLine( "{0:D5}\t{1:D24}\t{2:F24}\t{3:F24}", + i, + fib(i), + (1/(decimal)fib(i)), + fibConstant(i) ); + } + } +} diff --git a/16_linq/custom_sqo_1.cs b/16_linq/custom_sqo_1.cs new file mode 100644 index 0000000..d3d0ac6 --- /dev/null +++ b/16_linq/custom_sqo_1.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; + +public static class MySqoSet +{ + public static IEnumerable Where ( + this IEnumerable source, + System.Func predicate ) { + Console.WriteLine( "My Where implementation called." ); + return System.Linq.Enumerable.Where( source, + predicate ); + } + + public static IEnumerable Select ( + this IEnumerable source, + System.Func selector ) { + Console.WriteLine( "My Select implementation called." ); + return System.Linq.Enumerable.Select( source, + selector ); + } +} + +public class CustomSqo +{ + static void Main() { + int[] numbers = { 1, 2, 3, 4 }; + + var query = from x in numbers + where x % 2 == 0 + select x * 2; + + foreach( var item in query ) { + Console.WriteLine( item ); + } + } +} diff --git a/16_linq/group_1.cs b/16_linq/group_1.cs new file mode 100644 index 0000000..296a626 --- /dev/null +++ b/16_linq/group_1.cs @@ -0,0 +1,24 @@ +using System; +using System.Linq; + +public class GroupExample +{ + static void Main() { + int[] numbers = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + }; + + // partition numbers into odd and + // even numbers. + var query = from x in numbers + group x by x % 2; + + foreach( var group in query ) { + Console.WriteLine( "mod2 == {0}", group.Key ); + foreach( var number in group ) { + Console.Write( "{0}, ", number ); + } + Console.WriteLine( "\n" ); + } + } +} diff --git a/16_linq/group_2.cs b/16_linq/group_2.cs new file mode 100644 index 0000000..d9111c1 --- /dev/null +++ b/16_linq/group_2.cs @@ -0,0 +1,52 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string LastName { get; set; } + public string FirstName { get; set; } + public string Nationality { get; set; } +} + +public class OrderByExample +{ + static void Main() { + var employees = new List() { + new Employee { + LastName = "Jones", FirstName = "Ed", + Nationality = "American" + }, + new Employee { + LastName = "Ivanov", FirstName = "Vasya", + Nationality = "Russian" + }, + new Employee { + LastName = "Jones", FirstName = "Tom", + Nationality = "Welsh" + }, + new Employee { + LastName = "Smails", FirstName = "Spaulding", + Nationality = "Irish" + }, + new Employee { + LastName = "Ivanov", FirstName = "Ivan", + Nationality = "Russian" + } + }; + + var query = from emp in employees + group emp by new { + Nationality = emp.Nationality, + LastName = emp.LastName + }; + + foreach( var group in query ) { + Console.WriteLine( group.Key ); + foreach( var employee in group ) { + Console.WriteLine( employee.FirstName ); + } + Console.WriteLine(); + } + } +} diff --git a/16_linq/infinite_1.cs b/16_linq/infinite_1.cs new file mode 100644 index 0000000..4dee0ef --- /dev/null +++ b/16_linq/infinite_1.cs @@ -0,0 +1,22 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class InfiniteList +{ + static IEnumerable AllIntegers() { + int count = 0; + while( true ) { + yield return count++; + } + } + + static void Main() { + var query = from number in AllIntegers() + select number * 2 + 1; + + foreach( var item in query.Take(10) ) { + Console.WriteLine( item ); + } + } +} diff --git a/16_linq/infinite_2.cs b/16_linq/infinite_2.cs new file mode 100644 index 0000000..c7f8758 --- /dev/null +++ b/16_linq/infinite_2.cs @@ -0,0 +1,25 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class InfiniteList +{ + static IEnumerable AllIntegers() { + int count = 0; + while( true ) { + yield return count++; + } + } + + static void Main() { + var query = from number in AllIntegers() + orderby number descending + select number * 2 + 1; + + IEnumerator results = query.GetEnumerator(); + for( int i = 0; i < 10; ++i ) { + results.MoveNext(); + Console.WriteLine( results.Current ); + } + } +} diff --git a/16_linq/into_1.cs b/16_linq/into_1.cs new file mode 100644 index 0000000..535887f --- /dev/null +++ b/16_linq/into_1.cs @@ -0,0 +1,31 @@ +using System; +using System.Linq; + +public class GroupExample +{ + static void Main() { + int[] numbers = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + }; + + // partition numbers into odd and + // even numbers. + var query = from x in numbers + group x by x % 2 into partition + where partition.Key == 0 + select new { + Key = partition.Key, + Count = partition.Count(), + Group = partition + }; + + foreach( var item in query ) { + Console.WriteLine( "mod2 == {0}", item.Key ); + Console.WriteLine( "Count == {0}", item.Count ); + foreach( var number in item.Group ) { + Console.Write( "{0}, ", number ); + } + Console.WriteLine( "\n" ); + } + } +} diff --git a/16_linq/into_2.cs b/16_linq/into_2.cs new file mode 100644 index 0000000..69cae91 --- /dev/null +++ b/16_linq/into_2.cs @@ -0,0 +1,30 @@ +using System; +using System.Linq; + +public class GroupExample +{ + static void Main() { + int[] numbers = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 + }; + + // partition numbers into odd and + // even numbers. + var query = from x in numbers + group x by x % 2 into partition + select new { + Key = partition.Key, + Count = partition.Count(), + Group = partition + }; + + foreach( var item in query ) { + Console.WriteLine( "mod2 == {0}", item.Key ); + Console.WriteLine( "Count == {0}", item.Count ); + foreach( var number in item.Group ) { + Console.Write( "{0}, ", number ); + } + Console.WriteLine( "\n" ); + } + } +} diff --git a/16_linq/join_1.cs b/16_linq/join_1.cs new file mode 100644 index 0000000..a97b365 --- /dev/null +++ b/16_linq/join_1.cs @@ -0,0 +1,62 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class EmployeeId +{ + public string Id { get; set; } + public string Name { get; set; } +} + +public class EmployeeNationality +{ + public string Id { get; set; } + public string Nationality { get; set; } +} + +public class JoinExample +{ + static void Main() { + // Build employee collection + var employees = new List() { + new EmployeeId{ Id = "111-11-1111", + Name = "Ed Glasser" }, + new EmployeeId{ Id = "222-22-2222", + Name = "Spaulding Smails" }, + new EmployeeId{ Id = "333-33-3333", + Name = "Ivan Ivanov" }, + new EmployeeId{ Id = "444-44-4444", + Name = "Vasya Pupkin" } + }; + + // Build nationality collection. + var empNationalities = new List() { + new EmployeeNationality{ Id = "111-11-1111", + Nationality = "American" }, + new EmployeeNationality{ Id = "333-33-3333", + Nationality = "Russian" }, + new EmployeeNationality{ Id = "222-22-2222", + Nationality = "Irish" }, + new EmployeeNationality{ Id = "444-44-4444", + Nationality = "Russian" } + }; + + // Build query. + var query = from emp in employees + join n in empNationalities + on emp.Id equals n.Id + orderby n.Nationality descending + select new { + Id = emp.Id, + Name = emp.Name, + Nationality = n.Nationality + }; + + foreach( var person in query ) { + Console.WriteLine( "{0}, {1}, \t{2}", + person.Id, + person.Name, + person.Nationality ); + } + } +} diff --git a/16_linq/let_1.cs b/16_linq/let_1.cs new file mode 100644 index 0000000..a9c5bd7 --- /dev/null +++ b/16_linq/let_1.cs @@ -0,0 +1,39 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string LastName { get; set; } + public string FirstName { get; set; } +} + +public class OrderByExample +{ + static void Main() { + var employees = new List() { + new Employee { + LastName = "Glasser", FirstName = "Ed" + }, + new Employee { + LastName = "Pupkin", FirstName = "Vasya" + }, + new Employee { + LastName = "Smails", FirstName = "Spaulding" + }, + new Employee { + LastName = "Ivanov", FirstName = "Ivan" + } + }; + + var query = from emp in employees + let fullName = emp.FirstName + + " " + emp.LastName + orderby fullName + select fullName; + + foreach( var item in query ) { + Console.WriteLine( item ); + } + } +} diff --git a/16_linq/let_2.cs b/16_linq/let_2.cs new file mode 100644 index 0000000..a3edb61 --- /dev/null +++ b/16_linq/let_2.cs @@ -0,0 +1,23 @@ +using System; +using System.Linq; + +public class MultTable +{ + static void Main() { + var query = from x in Enumerable.Range(0,10) + let innerRange = Enumerable.Range(0, 10) + from y in innerRange + select new { + X = x, + Y = y, + Product = x * y + }; + + foreach( var item in query ) { + Console.WriteLine( "{0} * {1} = {2}", + item.X, + item.Y, + item.Product ); + } + } +} diff --git a/16_linq/linq_onto_console_1.cs b/16_linq/linq_onto_console_1.cs new file mode 100644 index 0000000..d933fdc --- /dev/null +++ b/16_linq/linq_onto_console_1.cs @@ -0,0 +1,24 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public static class Extensions +{ + public static string Join( this string str, + IEnumerable list ) { + return string.Join( str, list.ToArray() ); + } +} + +public class Test +{ + static void Main() { + var numbers = new int[] { 5, 8, 3, 4 }; + + Console.WriteLine( + string.Join(", ", + (from x in numbers + orderby x + select x.ToString()).ToArray()) ); + } +} diff --git a/16_linq/multiple_from_1.cs b/16_linq/multiple_from_1.cs new file mode 100644 index 0000000..406f92b --- /dev/null +++ b/16_linq/multiple_from_1.cs @@ -0,0 +1,22 @@ +using System; +using System.Linq; + +public class MultTable +{ + static void Main() { + var query = from x in Enumerable.Range(0,10) + from y in Enumerable.Range(0,10) + select new { + X = x, + Y = y, + Product = x * y + }; + + foreach( var item in query ) { + Console.WriteLine( "{0} * {1} = {2}", + item.X, + item.Y, + item.Product ); + } + } +} diff --git a/16_linq/non_generic_linq_1.cs b/16_linq/non_generic_linq_1.cs new file mode 100644 index 0000000..04112d2 --- /dev/null +++ b/16_linq/non_generic_linq_1.cs @@ -0,0 +1,19 @@ +using System; +using System.Linq; +using System.Collections; + +public class NonGenericLinq +{ + static void Main() { + ArrayList numbers = new ArrayList(); + numbers.Add( 1 ); + numbers.Add( 2 ); + + var query = from int n in numbers + select n * 2; + + foreach( var item in query ) { + Console.WriteLine( item ); + } + } +} diff --git a/16_linq/orderby_1.cs b/16_linq/orderby_1.cs new file mode 100644 index 0000000..624a16f --- /dev/null +++ b/16_linq/orderby_1.cs @@ -0,0 +1,47 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string LastName { get; set; } + public string FirstName { get; set; } + public string Nationality { get; set; } +} + +public class OrderByExample +{ + static void Main() { + var employees = new List() { + new Employee { + LastName = "Glasser", FirstName = "Ed", + Nationality = "American" + }, + new Employee { + LastName = "Pupkin", FirstName = "Vasya", + Nationality = "Russian" + }, + new Employee { + LastName = "Smails", FirstName = "Spaulding", + Nationality = "Irish" + }, + new Employee { + LastName = "Ivanov", FirstName = "Ivan", + Nationality = "Russian" + } + }; + + var query = from emp in employees + orderby emp.Nationality, + emp.LastName descending, + emp.FirstName descending + select emp; + + foreach( var item in query ) { + Console.WriteLine( "{0},\t{1},\t{2}", + item.LastName, + item.FirstName, + item.Nationality ); + } + } +} diff --git a/16_linq/projector_1.cs b/16_linq/projector_1.cs new file mode 100644 index 0000000..c9a656b --- /dev/null +++ b/16_linq/projector_1.cs @@ -0,0 +1,28 @@ +using System; +using System.Linq; + +public class Result +{ + public Result( int input, int output ) { + Input = input; + Output = output; + } + public int Input { get; set; } + public int Output { get; set; } +} + +public class Projector +{ + static void Main() { + int[] numbers = { 1, 2, 3, 4 }; + + var query = from x in numbers + select new Result( x, x*2 ); + + foreach( var item in query ) { + Console.WriteLine( "Input = {0}, Output = {1}", + item.Input, + item.Output ); + } + } +} diff --git a/16_linq/projector_2.cs b/16_linq/projector_2.cs new file mode 100644 index 0000000..4ed9302 --- /dev/null +++ b/16_linq/projector_2.cs @@ -0,0 +1,20 @@ +using System; +using System.Linq; + +public class Projector +{ + static void Main() { + int[] numbers = { 1, 2, 3, 4 }; + + var query = from x in numbers + select new { + Input = x, + Output = x*2 }; + + foreach( var item in query ) { + Console.WriteLine( "Input = {0}, Output = {1}", + item.Input, + item.Output ); + } + } +} diff --git a/16_linq/simple_query_1.cs b/16_linq/simple_query_1.cs new file mode 100644 index 0000000..093004f --- /dev/null +++ b/16_linq/simple_query_1.cs @@ -0,0 +1,49 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string FirstName { get; set; } + public string LastName { get; set; } + public Decimal Salary { get; set; } + public DateTime StartDate { get; set; } +} + +public class SimpleQuery +{ + static void Main() { + // Create our database of employees. + var employees = new List { + new Employee { + FirstName = "Joe", + LastName = "Bob", + Salary = 94000, + StartDate = DateTime.Parse("1/4/1992") }, + new Employee { + FirstName = "Jane", + LastName = "Doe", + Salary = 123000, + StartDate = DateTime.Parse("4/12/1998") }, + new Employee { + FirstName = "Milton", + LastName = "Waddams", + Salary = 1000000, + StartDate = DateTime.Parse("12/3/1969") } + }; + + var query = from employee in employees + where employee.Salary > 100000 + orderby employee.LastName, employee.FirstName + select new { LastName = employee.LastName, + FirstName = employee.FirstName }; + + Console.WriteLine( "Highly paid employees:" ); + foreach( var item in query ) { + Console.WriteLine( "{0}, {1}", + item.LastName, + item.FirstName ); + } + + } +} diff --git a/16_linq/simple_query_1a.cs b/16_linq/simple_query_1a.cs new file mode 100644 index 0000000..f7ffef0 --- /dev/null +++ b/16_linq/simple_query_1a.cs @@ -0,0 +1,48 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string FirstName { get; set; } + public string LastName { get; set; } + public Decimal Salary { get; set; } + public DateTime StartDate { get; set; } +} + +public class SimpleQuery +{ + static void Main() { + // Create our database of employees. + var employees = new List { + new Employee { + FirstName = "Joe", + LastName = "Bob", + Salary = 94000, + StartDate = DateTime.Parse("1/4/1992") }, + new Employee { + FirstName = "Jane", + LastName = "Doe", + Salary = 123000, + StartDate = DateTime.Parse("4/12/1998") }, + new Employee { + FirstName = "Milton", + LastName = "Waddams", + Salary = 1000000, + StartDate = DateTime.Parse("12/3/1969") } + }; + + var query = from employee in employees + where employee.Salary > 100000 + select new { LastName = employee.LastName, + FirstName = employee.FirstName }; + + Console.WriteLine( "Highly paid employees:" ); + foreach( var item in query ) { + Console.WriteLine( "{0}, {1}", + item.LastName, + item.FirstName ); + } + + } +} diff --git a/16_linq/simple_query_2.cs b/16_linq/simple_query_2.cs new file mode 100644 index 0000000..42f1554 --- /dev/null +++ b/16_linq/simple_query_2.cs @@ -0,0 +1,50 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string FirstName { get; set; } + public string LastName { get; set; } + public Decimal Salary { get; set; } + public DateTime StartDate { get; set; } +} + +public class SimpleQuery +{ + static void Main() { + // Create our database of employees. + var employees = new List { + new Employee { + FirstName = "Joe", + LastName = "Bob", + Salary = 94000, + StartDate = DateTime.Parse("1/4/1992") }, + new Employee { + FirstName = "Jane", + LastName = "Doe", + Salary = 123000, + StartDate = DateTime.Parse("4/12/1998") }, + new Employee { + FirstName = "Milton", + LastName = "Waddams", + Salary = 1000000, + StartDate = DateTime.Parse("12/3/1969") } + }; + + var query = employees + .Where( emp => emp.Salary > 100000 ) + .OrderBy( emp => emp.LastName ) + .OrderBy( emp => emp.FirstName ) + .Select( emp => new {LastName = emp.LastName, + FirstName = emp.FirstName} ); + + Console.WriteLine( "Highly paid employees:" ); + foreach( var item in query ) { + Console.WriteLine( "{0}, {1}", + item.LastName, + item.FirstName ); + } + + } +} diff --git a/16_linq/simple_query_3.cs b/16_linq/simple_query_3.cs new file mode 100644 index 0000000..5ca9f9a --- /dev/null +++ b/16_linq/simple_query_3.cs @@ -0,0 +1,54 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class Employee +{ + public string FirstName { get; set; } + public string LastName { get; set; } + public Decimal Salary { get; set; } + public DateTime StartDate { get; set; } +} + +public class SimpleQuery +{ + static void Main() { + // Create our database of employees. + var employees = new List { + new Employee { + FirstName = "Joe", + LastName = "Bob", + Salary = 94000, + StartDate = DateTime.Parse("1/4/1992") }, + new Employee { + FirstName = "Jane", + LastName = "Doe", + Salary = 123000, + StartDate = DateTime.Parse("4/12/1998") }, + new Employee { + FirstName = "Milton", + LastName = "Waddams", + Salary = 1000000, + StartDate = DateTime.Parse("12/3/1969") } + }; + + var query = + Enumerable.Select( + Enumerable.OrderBy( + Enumerable.OrderBy( + Enumerable.Where( + employees, emp => emp.Salary > 100000), + emp => emp.LastName ), + emp => emp.FirstName ), + emp => new {LastName = emp.LastName, + FirstName = emp.FirstName} ); + + Console.WriteLine( "Highly paid employees:" ); + foreach( var item in query ) { + Console.WriteLine( "{0}, {1}", + item.LastName, + item.FirstName ); + } + + } +} diff --git a/16_linq/sort_non_enum_1.cs b/16_linq/sort_non_enum_1.cs new file mode 100644 index 0000000..1bd2d69 --- /dev/null +++ b/16_linq/sort_non_enum_1.cs @@ -0,0 +1,115 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, CreateList(iter) ); + } + + public MyList( T head, IList tail ) { + this.head = head; + this.tail = tail; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + return tail; + } + } + + private T head; + private IList tail; +} + +public static class MyListExtensions +{ + public static IEnumerable + GeneralIterator( this IList theList, + Func, bool> finalState, + Func, IList> incrementer ) { + while( !finalState(theList) ) { + yield return theList.Head; + theList = incrementer( theList ); + } + } + + public static IList Where( this IList theList, + Func predicate ) { + Func, IList> whereFunc = null; + + whereFunc = list => { + IList result = new MyList(default(T), null); + + if( list.Tail != null ) { + if( predicate(list.Head) ) { + result = new MyList( list.Head, whereFunc(list.Tail) ); + } else { + result = whereFunc( list.Tail ); + } + } + + return result; + }; + + return whereFunc( theList ); + } + + public static IList Select( this IList theList, + Func selector ) { + Func, IList> selectorFunc = null; + + selectorFunc = list => { + IList result = new MyList(default(R), null); + + if( list.Tail != null ) { + result = new MyList( selector(list.Head), selectorFunc(list.Tail) ); + } + + return result; + }; + + return selectorFunc( theList ); + } +} + +public class SqoExample +{ + static void Main() { + var listInts = new List { 5, 2, 9, 4, 3, 1 }; + var linkList = + MyList.CreateList( listInts ); + + // Now sort. + var linkList2 = linkList.Where( x => x > 3 ).Select( x => x * 2 ); + var iterator2 = linkList2.GeneralIterator( list => list.Tail == null, + list => list.Tail ); + foreach( var item in iterator2 ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/16_linq/sort_non_enum_2.cs b/16_linq/sort_non_enum_2.cs new file mode 100644 index 0000000..b65ff5f --- /dev/null +++ b/16_linq/sort_non_enum_2.cs @@ -0,0 +1,167 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public interface IList +{ + T Head { get; } + IList Tail { get; } +} + +public class MyList : IList +{ + public static IList CreateList( IEnumerable items ) { + IEnumerator iter = items.GetEnumerator(); + return CreateList( iter ); + } + + public static IList CreateList( IEnumerator iter ) { + Func> tailGenerator = null; + tailGenerator = () => { + if( !iter.MoveNext() ) { + return new MyList( default(T), null ); + } + + return new MyList( iter.Current, tailGenerator ); + }; + + return tailGenerator(); + } + + public MyList( T head, Func> tailGenerator ) { + this.head = head; + this.tailGenerator = tailGenerator; + } + + public T Head { + get { + return head; + } + } + + public IList Tail { + get { + if( tailGenerator == null ) { + return null; + } else if( tail == null ) { + tail = tailGenerator(); + } + return tail; + } + } + + private T head; + private Func> tailGenerator; + private IList tail = null; +} + +public static class MyListExtensions +{ + public static IEnumerable + GeneralIterator( this IList theList, + Func,bool> finalState, + Func,IList> incrementer ) { + while( !finalState(theList) ) { + yield return theList.Head; + theList = incrementer( theList ); + } + } + + public static IList Where( this IList theList, + Func predicate ) { + Func> whereTailFunc = null; + + whereTailFunc = () => { + IList result = null; + + if( theList.Tail == null ) { + result = new MyList( default(T), null ); + } + + if( predicate(theList.Head) ) { + result = new MyList( theList.Head, + whereTailFunc ); + } + + theList = theList.Tail; + if( result == null ) { + result = whereTailFunc(); + } + + return result; + }; + + return whereTailFunc(); + } + + public static IList Select( this IList theList, + Func selector ) { + Func> selectorTailFunc = null; + + selectorTailFunc = () => { + IList result = null; + + if( theList.Tail == null ) { + result = new MyList( default(R), null ); + } else { + result = new MyList( selector(theList.Head), + selectorTailFunc ); + } + + theList = theList.Tail; + return result; + }; + + return selectorTailFunc(); + } + + public static IList Take( this IList theList, + int count ) { + Func> takeTailFunc = null; + + takeTailFunc = () => { + IList result = null; + + if( theList.Tail == null || count-- == 0 ) { + result = new MyList( default(T), null ); + } else { + result = new MyList( theList.Head, + takeTailFunc ); + } + + theList = theList.Tail; + return result; + }; + + return takeTailFunc(); + } +} + +public class SqoExample +{ + static IList CreateInfiniteList( T item ) { + Func> tailGenerator = null; + + tailGenerator = () => { + return new MyList( item, tailGenerator ); + }; + + return tailGenerator(); + } + + static void Main() { + var infiniteList = CreateInfiniteList( 21 ); + + var linkList = infiniteList.Where( x => x > 3 ) + .Select( x => x * 2 ) + .Take( 10 ); + var iterator = linkList.GeneralIterator( + list => list.Tail == null, + list => list.Tail ); + foreach( var item in iterator ) { + Console.Write( "{0}, ", item ); + } + + Console.WriteLine(); + } +} diff --git a/16_linq/test.cs b/16_linq/test.cs new file mode 100644 index 0000000..81cb51d --- /dev/null +++ b/16_linq/test.cs @@ -0,0 +1,81 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +public class EmployeeId +{ + public string Id { get; set; } + public string Name { get; set; } +} + +public class EmployeeNationality +{ + public string Id { get; set; } + public string Nationality { get; set; } +} + +public class LangSpoken +{ + public string Nationality { get; set; } + public string Language { get; set; } +} + +public class JoinExample +{ + static void Main() { + // Build employee collection + var employees = new List() { + new EmployeeId{ Id = "111-11-1111", + Name = "Ed Glasser" }, + new EmployeeId{ Id = "222-22-2222", + Name = "Spaulding Smails" }, + new EmployeeId{ Id = "333-33-3333", + Name = "Ivan Ivanov" }, + new EmployeeId{ Id = "444-44-4444", + Name = "Vasya Pupkin" } + }; + + // Build nationality collection. + var empNationalities = new List() { + new EmployeeNationality{ Id = "111-11-1111", + Nationality = "American" }, + new EmployeeNationality{ Id = "333-33-3333", + Nationality = "Russian" }, + new EmployeeNationality{ Id = "222-22-2222", + Nationality = "Irish" }, + new EmployeeNationality{ Id = "444-44-4444", + Nationality = "Russian" } + }; + + var langSpoken = new List() { + new LangSpoken{ Nationality = "Russian", + Language = "Russian" }, + new LangSpoken{ Nationality = "Irish", + Language = "The Queen's English" }, + new LangSpoken{ Nationality = "American", + Language = "Refined English" } + }; + + // Build query. + var query = from emp in employees + join n in empNationalities + on emp.Id equals n.Id + join l in langSpoken + on n.Nationality equals l.Nationality + orderby n.Nationality descending + select new { + Id = emp.Id, + Name = emp.Name, + Nationality = n.Nationality, + Language = l.Language + }; + + foreach( var person in query ) { + Console.WriteLine( "{0}, {1}, \t{2}\t {3}", + person.Id, + person.Name, + person.Nationality, + person.Language ); + } + } +} diff --git a/3828.pdf b/3828.pdf new file mode 100644 index 0000000..3203a86 Binary files /dev/null and b/3828.pdf differ diff --git a/3829.pdf b/3829.pdf new file mode 100644 index 0000000..bab5e56 Binary files /dev/null and b/3829.pdf differ diff --git a/3_syntax_overview/3_generics_1.cs b/3_syntax_overview/3_generics_1.cs new file mode 100644 index 0000000..f7ddc79 --- /dev/null +++ b/3_syntax_overview/3_generics_1.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +class EntryPoint +{ + static void Main() { + Collection numbers = + new Collection(); + numbers.Add( 42 ); + numbers.Add( 409 ); + + Collection strings = + new Collection(); + strings.Add( "Joe" ); + strings.Add( "Bob" ); + + Collection< Collection > colNumbers + = new Collection>(); + colNumbers.Add( numbers ); + + IList theNumbers = numbers; + foreach( int i in theNumbers ) { + Console.WriteLine( i ); + } + } +} diff --git a/3_syntax_overview/as_1.cs b/3_syntax_overview/as_1.cs new file mode 100644 index 0000000..031b0ee --- /dev/null +++ b/3_syntax_overview/as_1.cs @@ -0,0 +1,39 @@ +using System; + +public class BaseType +{ +} + +public class DerivedType : BaseType +{ +} + +public class EntryPoint +{ + static void Main() { + DerivedType derivedObj = new DerivedType(); + BaseType baseObj1 = new BaseType(); + BaseType baseObj2 = derivedObj; + + DerivedType derivedObj2 = baseObj2 as DerivedType; + if( derivedObj2 != null ) { + Console.WriteLine( "Conversion Succeeded" ); + } else { + Console.WriteLine( "Conversion Failed" ); + } + + derivedObj2 = baseObj1 as DerivedType; + if( derivedObj2 != null ) { + Console.WriteLine( "Conversion Succeeded" ); + } else { + Console.WriteLine( "Conversion Failed" ); + } + + BaseType baseObj3 = derivedObj as BaseType; + if( baseObj3 != null ) { + Console.WriteLine( "Conversion Succeeded" ); + } else { + Console.WriteLine( "Conversion Failed" ); + } + } +} diff --git a/3_syntax_overview/boxing.cs b/3_syntax_overview/boxing.cs new file mode 100644 index 0000000..02e6621 --- /dev/null +++ b/3_syntax_overview/boxing.cs @@ -0,0 +1,13 @@ +public class EntryPoint +{ + static void Main() { + int employeeID = 303; + object boxedID = employeeID; + + employeeID = 404; + int unboxedID = (int) boxedID; + + System.Console.WriteLine( employeeID.ToString() ); + System.Console.WriteLine( unboxedID.ToString() ); + } +} diff --git a/3_syntax_overview/conversions_1.cs b/3_syntax_overview/conversions_1.cs new file mode 100644 index 0000000..336f5e7 --- /dev/null +++ b/3_syntax_overview/conversions_1.cs @@ -0,0 +1,9 @@ +public class EntryPoint +{ + static void Main() { + string[] names = new string[4]; + object[] objects = names; + + string[] originalNames = (string[]) objects; + } +} diff --git a/3_syntax_overview/implicit_type_1.cs b/3_syntax_overview/implicit_type_1.cs new file mode 100644 index 0000000..1faf4ef --- /dev/null +++ b/3_syntax_overview/implicit_type_1.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + var myList = new List(); + + myList.Add( 1 ); + myList.Add( 2 ); + myList.Add( 3 ); + + foreach( var i in myList ) { + Console.WriteLine( i ); + } + } +} diff --git a/3_syntax_overview/is_1.cs b/3_syntax_overview/is_1.cs new file mode 100644 index 0000000..7735cbc --- /dev/null +++ b/3_syntax_overview/is_1.cs @@ -0,0 +1,29 @@ +using System; + +public class EntryPoint +{ + static void Main() { + String derivedObj = "Dummy"; + Object baseObj1 = new Object(); + Object baseObj2 = derivedObj; + + Console.WriteLine( "baseObj2 {0} String", + baseObj2 is String ? "is" : "isnot" ); + Console.WriteLine( "baseObj1 {0} String", + baseObj1 is String ? "is" : "isnot" ); + Console.WriteLine( "derivedObj {0} Object", + derivedObj is Object ? "is" : "isnot" ); + + int j = 123; + object boxed = j; + object obj = new Object(); + + Console.WriteLine( "boxed {0} int", + boxed is int ? "is" : "isnot" ); + Console.WriteLine( "obj {0} int", + obj is int ? "is" : "isnot" ); + Console.WriteLine( "boxed {0} System.ValueType", + boxed is ValueType ? "is" : "isnot" ); + + } +} diff --git a/3_syntax_overview/references_1.cs b/3_syntax_overview/references_1.cs new file mode 100644 index 0000000..77d2d93 --- /dev/null +++ b/3_syntax_overview/references_1.cs @@ -0,0 +1,19 @@ +public class Employee +{ + public string name; +} + +public class EntryPoint +{ + private static void InspectEmployee( Employee someEmployee ) { + someEmployee.name = "Jane"; + } + + static void Main() { + Employee joe = new Employee(); + joe.name = "Joe"; + InspectEmployee( joe ); + + System.Console.WriteLine( "Employee name: {0}", joe.name ); + } +} diff --git a/3_syntax_overview/references_2.cs b/3_syntax_overview/references_2.cs new file mode 100644 index 0000000..ba34e33 --- /dev/null +++ b/3_syntax_overview/references_2.cs @@ -0,0 +1,19 @@ +public class Employee +{ + public string name; +} + +public class EntryPoint +{ + private static void CreateEmployee( Employee someEmployee ) { + someEmployee = new Employee(); + someEmployee.name = "Joe"; + } + + static void Main() { + Employee joe = null; + CreateEmployee( joe ); + + System.Console.WriteLine( "Employee name: {0}", joe.name ); + } +} diff --git a/3_syntax_overview/references_3.cs b/3_syntax_overview/references_3.cs new file mode 100644 index 0000000..6ccebb2 --- /dev/null +++ b/3_syntax_overview/references_3.cs @@ -0,0 +1,19 @@ +public class Employee +{ + public string name; +} + +public class EntryPoint +{ + private static void CreateEmployee( ref Employee someEmployee ) { + someEmployee = new Employee(); + someEmployee.name = "Joe"; + } + + static void Main() { + Employee joe = null; + CreateEmployee( ref joe ); + + System.Console.WriteLine( "Employee name: {0}", joe.name ); + } +} diff --git a/3_syntax_overview/values_1.cs b/3_syntax_overview/values_1.cs new file mode 100644 index 0000000..1fd835b --- /dev/null +++ b/3_syntax_overview/values_1.cs @@ -0,0 +1,30 @@ +public struct Coordinate +{ + public int x; + public int y; +} + +public class EntryPoint +{ + public static void AttemptToModifyCoord( Coordinate coord ) { + coord.x = 1; + coord.y = 3; + } + + public static void ModifyCoord( ref Coordinate coord ) { + coord.x = 10; + coord.y = 10; + } + + static void Main() { + Coordinate location; + location.x = 50; + location.y = 50; + + AttemptToModifyCoord( location ); + System.Console.WriteLine( "( {0}, {1} )", location.x, location.y ); + + ModifyCoord( ref location ); + System.Console.WriteLine( "( {0}, {1} )", location.x, location.y ); + } +} diff --git a/4_classes_structs/4_abstract_classes_1.cs b/4_classes_structs/4_abstract_classes_1.cs new file mode 100644 index 0000000..78fb81b --- /dev/null +++ b/4_classes_structs/4_abstract_classes_1.cs @@ -0,0 +1,25 @@ +public abstract class GeometricShape +{ + public abstract void Draw(); +} + +public class Circle : GeometricShape +{ + public override void Draw() + { + // Do some drawing. + } +} + +public class EntryPoint +{ + static void Main() + { + Circle shape = new Circle(); + + // This won't work! + // GeometricShape shape2 = new GeometricShape(); + + shape.Draw(); + } +} diff --git a/4_classes_structs/4_beforefieldinit_1.cs b/4_classes_structs/4_beforefieldinit_1.cs new file mode 100644 index 0000000..202dbba --- /dev/null +++ b/4_classes_structs/4_beforefieldinit_1.cs @@ -0,0 +1,26 @@ +using System; + +public class A +{ + public A() + { + Console.WriteLine( "A.A()" ); + } + + static int InitX() + { + Console.WriteLine( "A.InitX()" ); + return 1; + } + + public int x = InitX(); +} + +public class EntryPoint +{ + static void Main() + { + // No guarantee A.InitX() is called before this! + A a = new A(); + } +} diff --git a/4_classes_structs/4_box_1.cs b/4_classes_structs/4_box_1.cs new file mode 100644 index 0000000..c03e317 --- /dev/null +++ b/4_classes_structs/4_box_1.cs @@ -0,0 +1,12 @@ +public class EntryPoint +{ + static void Print( object obj ) + { + System.Console.WriteLine( "{0}", obj.ToString() ); + } + static void Main() + { + int x = 42; + Print( x ); + } +} diff --git a/4_classes_structs/4_box_2.cs b/4_classes_structs/4_box_2.cs new file mode 100644 index 0000000..ff9cf79 --- /dev/null +++ b/4_classes_structs/4_box_2.cs @@ -0,0 +1,15 @@ +public class EntryPoint +{ + static void PrintAndModify( object obj ) + { + System.Console.WriteLine( "{0}", obj.ToString() ); + int x = (int) obj; + x = 21; + } + static void Main() + { + int x = 42; + PrintAndModify( x ); + PrintAndModify( x ); + } +} diff --git a/4_classes_structs/4_box_3.cs b/4_classes_structs/4_box_3.cs new file mode 100644 index 0000000..d004b58 --- /dev/null +++ b/4_classes_structs/4_box_3.cs @@ -0,0 +1,57 @@ +public interface IModifyMyValue +{ + int X + { + get; + set; + } +} + +public struct MyValue : IModifyMyValue +{ + public int x; + + public int X + { + get + { + return x; + } + + set + { + x = value; + } + } + + public override string ToString() + { + System.Text.StringBuilder output = + new System.Text.StringBuilder(); + output.AppendFormat( "{0}", x ); + return output.ToString(); + } +} + +public class EntryPoint +{ + static void Main() + { + // Create value + MyValue myval = new MyValue(); + myval.x = 123; + + // box it + object obj = myval; + System.Console.WriteLine( "{0}", obj.ToString() ); + + // modify the contents in the box. + IModifyMyValue iface = (IModifyMyValue) obj; + iface.X = 456; + System.Console.WriteLine( "{0}", obj.ToString() ); + + // unbox it and see what it is. + MyValue newval = (MyValue) obj; + System.Console.WriteLine( "{0}", newval.ToString() ); + } +} diff --git a/4_classes_structs/4_box_4.cs b/4_classes_structs/4_box_4.cs new file mode 100644 index 0000000..a04eb06 --- /dev/null +++ b/4_classes_structs/4_box_4.cs @@ -0,0 +1,30 @@ +public interface IPrint +{ + void Print(); +} + +public struct MyValue : IPrint +{ + public int x; + + public void Print() + { + System.Console.WriteLine( "{0}", x ); + } +} + +public class EntryPoint +{ + static void Main() + { + MyValue myval = new MyValue(); + myval.x = 123; + + // no boxing + myval.Print(); + + // must box the value + IPrint printer = myval; + printer.Print(); + } +} diff --git a/4_classes_structs/4_box_5.cs b/4_classes_structs/4_box_5.cs new file mode 100644 index 0000000..ab0dcfe --- /dev/null +++ b/4_classes_structs/4_box_5.cs @@ -0,0 +1,27 @@ +public interface IPrint +{ + void Print(); +} + +public struct MyValue : IPrint +{ + public int x; + + void IPrint.Print() + { + System.Console.WriteLine( "{0}", x ); + } +} + +public class EntryPoint +{ + static void Main() + { + MyValue myval = new MyValue(); + myval.x = 123; + + // must box the value + IPrint printer = myval; + printer.Print(); + } +} diff --git a/4_classes_structs/4_class_definition_1.cs b/4_classes_structs/4_class_definition_1.cs new file mode 100644 index 0000000..b6df7dc --- /dev/null +++ b/4_classes_structs/4_class_definition_1.cs @@ -0,0 +1,13 @@ +[Serializable] +public class Derived : Base, ICloneable +{ + private Derived( Derived other ) { + this.x = other.x; + } + + public object Clone() { + return new Derived( this ); + } + + private int x; +} diff --git a/4_classes_structs/4_compareto_1.cs b/4_classes_structs/4_compareto_1.cs new file mode 100644 index 0000000..2fd9e69 --- /dev/null +++ b/4_classes_structs/4_compareto_1.cs @@ -0,0 +1,90 @@ +public class ComplexNumber : System.IComparable +{ + public ComplexNumber( int real, int imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + public override bool Equals( object obj ) + { + ComplexNumber other = obj as ComplexNumber; + + if( other == null ) + { + return false; + } + + return (this.real == other.real) && + (this.imaginary == other.imaginary); + } + + public override int GetHashCode() + { + return (int) real ^ (int) imaginary; + } + + public static bool operator==( ComplexNumber me, ComplexNumber other ) + { + return Equals( me, other ); + } + + public static bool operator!=( ComplexNumber me, ComplexNumber other ) + { + return Equals( me, other ); + } + + public double Magnitude + { + get + { + return System.Math.Sqrt( System.Math.Pow(this.real, 2) + + System.Math.Pow(this.imaginary, 2) ); + } + } + + public int CompareTo( object obj ) + { + if( obj is ComplexNumber ) + { + ComplexNumber other = (ComplexNumber) obj; + + if( (this.real == other.real) && + (this.imaginary == other.imaginary) ) + { + return 0; + } + else if( this.Magnitude < other.Magnitude ) + { + return -1; + } + else + { + return 1; + } + } + else + { + throw new System.ArgumentException( "Wrong type" ); + } + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() + { + ComplexNumber referenceA = new ComplexNumber( 1, 2 ); + ComplexNumber referenceB = new ComplexNumber( 1, 2 ); + ComplexNumber referenceC = new ComplexNumber( 1, 3 ); + + System.Console.WriteLine( "Result of referenceA.CompareTo(referenceB) is {0}", + referenceA.CompareTo(referenceB) ); + System.Console.WriteLine( "Result of referenceA.CompareTo(referenceC) is {0}", + referenceA.CompareTo(referenceC) ); + + } +} diff --git a/4_classes_structs/4_containment_example_1.cs b/4_classes_structs/4_containment_example_1.cs new file mode 100644 index 0000000..57a0708 --- /dev/null +++ b/4_classes_structs/4_containment_example_1.cs @@ -0,0 +1,12 @@ +public class NetworkCommunicator +{ + public void SendData( DataObject obj ) + { + // Send the data over the wire. + } + + public DataObject ReceiveData() + { + // Receive data over the wire. + } +} diff --git a/4_classes_structs/4_containment_example_2.cs b/4_classes_structs/4_containment_example_2.cs new file mode 100644 index 0000000..eecbb86 --- /dev/null +++ b/4_classes_structs/4_containment_example_2.cs @@ -0,0 +1,17 @@ +public class EncryptedNetworkCommunicator : NetworkCommunicator +{ + public override void SendData( DataObject obj ) + { + // Encrypt the data. + base.SendData( obj ); + } + + public override DataObject ReceiveData() + { + DataObject obj = base.ReceiveData(); + + // Decrypt data. + + return obj; + } +} diff --git a/4_classes_structs/4_containment_example_3.cs b/4_classes_structs/4_containment_example_3.cs new file mode 100644 index 0000000..e312f5f --- /dev/null +++ b/4_classes_structs/4_containment_example_3.cs @@ -0,0 +1,24 @@ +public class EncryptedNetworkCommunicator +{ + public EncryptedNetworkCommunicator() + { + contained = new NetworkCommunicator(); + } + + public void SendData( DataObject obj ) + { + // Encrypt the data. + contained.SendData( obj ); + } + + public DataObject ReceiveData() + { + DataObject obj = contained.ReceiveData(); + + // Decrypt data + + return obj; + } + + private NetworkCommunicator contained; +} diff --git a/4_classes_structs/4_ctor_struct_1.cs b/4_classes_structs/4_ctor_struct_1.cs new file mode 100644 index 0000000..a3c8f64 --- /dev/null +++ b/4_classes_structs/4_ctor_struct_1.cs @@ -0,0 +1,26 @@ +using System; + +public struct Square +{ + // Not a good idea to have public fields, but I use them + // here only for the sake of example. Prefer to expose + // these with properties instead. + public int width; + public int height; +} + +public class EntryPoint +{ + static void Main() + { + Square sq; + sq.width = 1; + + // Can't do this yet. + // Console.WriteLine( "{0} x {1}", sq.width, sq.height ); + + sq.height = 2; + + Console.WriteLine( "{0} x {1}", sq.width, sq.height ); + } +} diff --git a/4_classes_structs/4_ctor_struct_2.cs b/4_classes_structs/4_ctor_struct_2.cs new file mode 100644 index 0000000..8c44c4f --- /dev/null +++ b/4_classes_structs/4_ctor_struct_2.cs @@ -0,0 +1,43 @@ +using System; + +public struct Square +{ + public int Width + { + get + { + return width; + } + + set + { + width = value; + } + } + + public int Height + { + get + { + return height; + } + + set + { + height = value; + } + } + + private int width; + private int height; +} + +public class EntryPoint +{ + static void Main() + { + Square sq; + sq.Width = 1; + sq.Height = 1; + } +} diff --git a/4_classes_structs/4_ctor_struct_3.cs b/4_classes_structs/4_ctor_struct_3.cs new file mode 100644 index 0000000..a681b69 --- /dev/null +++ b/4_classes_structs/4_ctor_struct_3.cs @@ -0,0 +1,9 @@ +public class EntryPoint +{ + static void Main() + { + Square sq = new Square(); + sq.Width = 1; + sq.Height = 1; + } +} diff --git a/4_classes_structs/4_destructor_1.cs b/4_classes_structs/4_destructor_1.cs new file mode 100644 index 0000000..b1e80d9 --- /dev/null +++ b/4_classes_structs/4_destructor_1.cs @@ -0,0 +1,25 @@ +using System; + +public class Base +{ + ~Base() + { + Console.WriteLine( "Base.~Base()" ); + } +} + +public class Derived : Base +{ + ~Derived() + { + Console.WriteLine( "Derived.~Derived()" ); + } +} + +public class EntryPoint +{ + static void Main() + { + Derived derived = new Derived(); + } +} diff --git a/4_classes_structs/4_destructor_2.cs b/4_classes_structs/4_destructor_2.cs new file mode 100644 index 0000000..470b573 --- /dev/null +++ b/4_classes_structs/4_destructor_2.cs @@ -0,0 +1,33 @@ +using System; + +public class A +{ + ~A() + { + Console.WriteLine( "A.~A()" ); + + // Store away a reference to ourselves. + EntryPoint.obj = this; + } + + private object objA; + private object ojbB; +} + +public class EntryPoint +{ + internal static A obj; + + static void Main() + { + { + A a = new A(); + } + + // Force a collect. + GC.Collect(); + GC.WaitForPendingFinalizers(); + + Console.WriteLine( "Done" ); + } +} diff --git a/4_classes_structs/4_destructor_3.cs b/4_classes_structs/4_destructor_3.cs new file mode 100644 index 0000000..65b0b34 --- /dev/null +++ b/4_classes_structs/4_destructor_3.cs @@ -0,0 +1,34 @@ +using System; + +public class A +{ + ~A() + { + Console.WriteLine( "A.~A()" ); + + // Store away a reference to ourselves. + EntryPoint.obj = this; + GC.ReRegisterForFinalize( this ); + } + + private object objA; + private object ojbB; +} + +public class EntryPoint +{ + internal static A obj; + + static void Main() + { + { + A a = new A(); + } + + // Force a collect. + GC.Collect(); + GC.WaitForPendingFinalizers(); + + Console.WriteLine( "Done" ); + } +} diff --git a/4_classes_structs/4_disposable.cs b/4_classes_structs/4_disposable.cs new file mode 100644 index 0000000..867a57e --- /dev/null +++ b/4_classes_structs/4_disposable.cs @@ -0,0 +1,47 @@ +using System; + +public class A : IDisposable +{ + private bool disposed = false; + public void Dispose( bool disposing ) + { + if( !disposed ) { + if( disposing ) { + // It is safe to access other objects here. + } + + Console.WriteLine( "Cleaning up object" ); + disposed = true; + } + } + public void Dispose() + { + Dispose( true ); + GC.SuppressFinalize( this ); + } + + public void DoSomething() + { + Console.WriteLine( "A.SoSomething()" ); + } + + ~A() + { + Console.WriteLine( "Finalizing" ); + Dispose( false ); + } +} + +public class EntryPoint +{ + static void Main() + { + A a = new A(); + try { + a.DoSomething(); + } + finally { + a.Dispose(); + } + } +} diff --git a/4_classes_structs/4_disposable_2.cs b/4_classes_structs/4_disposable_2.cs new file mode 100644 index 0000000..eeb97c1 --- /dev/null +++ b/4_classes_structs/4_disposable_2.cs @@ -0,0 +1,48 @@ +using System; + +public class A : IDisposable +{ + private bool disposed = false; + public void Dispose( bool disposing ) + { + if( !disposed ) { + if( disposing ) { + // It is safe to access other objects here. + } + + Console.WriteLine( "Cleaning up object" ); + disposed = true; + } + } + public void Dispose() + { + Dispose( true ); + GC.SuppressFinalize( this ); + } + + public void DoSomething() + { + Console.WriteLine( "A.SoSomething()" ); + } + + ~A() + { + Console.WriteLine( "Finalizing" ); + Dispose( false ); + } +} + +public class EntryPoint +{ + static void Main() + { + using( A a = new A() ) { + a.DoSomething(); + } + + using( A a = new A(), b = new A() ) { + a.DoSomething(); + b.DoSomething(); + } + } +} diff --git a/4_classes_structs/4_encapsulation_example_1.cs b/4_classes_structs/4_encapsulation_example_1.cs new file mode 100644 index 0000000..0c801f5 --- /dev/null +++ b/4_classes_structs/4_encapsulation_example_1.cs @@ -0,0 +1,5 @@ +class MyRectangle +{ + public uint width; + public uint height; +} diff --git a/4_classes_structs/4_encapsulation_example_2.cs b/4_classes_structs/4_encapsulation_example_2.cs new file mode 100644 index 0000000..002652c --- /dev/null +++ b/4_classes_structs/4_encapsulation_example_2.cs @@ -0,0 +1,10 @@ +class MyRectangle +{ + public uint width; + public uint height; + + public uint GetArea() + { + return width * height; + } +} diff --git a/4_classes_structs/4_encapsulation_example_3.cs b/4_classes_structs/4_encapsulation_example_3.cs new file mode 100644 index 0000000..5190ceb --- /dev/null +++ b/4_classes_structs/4_encapsulation_example_3.cs @@ -0,0 +1,12 @@ +class MyRectangle +{ + public uint width; + public uint height; + + public uint area; + + public uint GetArea() + { + return area; + } +} diff --git a/4_classes_structs/4_encapsulation_example_4.cs b/4_classes_structs/4_encapsulation_example_4.cs new file mode 100644 index 0000000..102e8d5 --- /dev/null +++ b/4_classes_structs/4_encapsulation_example_4.cs @@ -0,0 +1,16 @@ +class MyRectangle +{ + public uint width; + public uint height; + + private uint area; + + public uint GetArea() + { + if( area == 0 ) { + area = width * height; + } + + return area; + } +} diff --git a/4_classes_structs/4_encapsulation_example_5.cs b/4_classes_structs/4_encapsulation_example_5.cs new file mode 100644 index 0000000..5dd528a --- /dev/null +++ b/4_classes_structs/4_encapsulation_example_5.cs @@ -0,0 +1,47 @@ +class MyRectangle +{ + private uint width; + private uint height; + private uint area; + + public uint Width + { + get + { + return width; + } + + set + { + width = value; + ComputeArea(); + } + } + + public uint Height + { + get + { + return height; + } + + set + { + height = value; + ComputeArea(); + } + } + + public uint Area + { + get + { + return area; + } + } + + private void ComputeArea() + { + area = width * height; + } +} diff --git a/4_classes_structs/4_equality_2.cs b/4_classes_structs/4_equality_2.cs new file mode 100644 index 0000000..94b5467 --- /dev/null +++ b/4_classes_structs/4_equality_2.cs @@ -0,0 +1,21 @@ +public class EntryPoint +{ + static bool TestForEquality( object obj1, object obj2 ) + { + if( obj1 == null ) + { + return false; + } + + return obj1.Equals( obj2 ); + } + + static void Main() + { + object obj1 = new System.Object(); + object obj2 = null; + + System.Console.WriteLine( "obj1 == obj2 is {0}", + TestForEquality(obj2, obj1) ); + } +} diff --git a/4_classes_structs/4_field_init_1.cs b/4_classes_structs/4_field_init_1.cs new file mode 100644 index 0000000..ef91862 --- /dev/null +++ b/4_classes_structs/4_field_init_1.cs @@ -0,0 +1,39 @@ +using System; + +public class A +{ + private static int InitX() + { + Console.WriteLine( "A.InitX()" ); + return 1; + } + private static int InitY() + { + Console.WriteLine( "A.InitY()" ); + return 2; + } + private static int InitA() + { + Console.WriteLine( "A.InitA()" ); + return 3; + } + private static int InitB() + { + Console.WriteLine( "A.InitB()" ); + return 4; + } + + private int y = InitY(); + private int x = InitX(); + + private static int a = InitA(); + private static int b = InitB(); +} + +public class EntryPoint +{ + static void Main() + { + A a = new A(); + } +} diff --git a/4_classes_structs/4_field_initializers_1.cs b/4_classes_structs/4_field_initializers_1.cs new file mode 100644 index 0000000..2d2c2b3 --- /dev/null +++ b/4_classes_structs/4_field_initializers_1.cs @@ -0,0 +1,24 @@ +public class A +{ + public A() + { + this.y = 123; + } + + private static int InitZ() + { + return 987; + } + + private int x = 789; + private int y; + private int z = A.InitZ(); + + static void Main() + { + A obj = new A(); + + System.Console.WriteLine( "x = {0}, y = {1}, z = {2}", + obj.x, obj.y, obj.z ); + } +} diff --git a/4_classes_structs/4_indexer_1.cs b/4_classes_structs/4_indexer_1.cs new file mode 100644 index 0000000..dace043 --- /dev/null +++ b/4_classes_structs/4_indexer_1.cs @@ -0,0 +1,71 @@ +using System.Collections; + +public abstract class GeometricShape +{ + public abstract void Draw(); +} + +public class Rectangle : GeometricShape +{ + public override void Draw() + { + System.Console.WriteLine( "Rectangle.Draw" ); + } +} + +public class Circle : GeometricShape +{ + public override void Draw() + { + System.Console.WriteLine( "Circle.Draw" ); + } +} + +public class Drawing +{ + private ArrayList shapes; + + public Drawing() + { + shapes = new ArrayList(); + } + + public int Count + { + get + { + return shapes.Count; + } + } + + public GeometricShape this[ int index ] + { + get + { + return (GeometricShape) shapes[index]; + } + } + + public void Add( GeometricShape shape ) + { + shapes.Add( shape ); + } +} + +public class EntryPoint +{ + static void Main() + { + Rectangle rectangle = new Rectangle(); + Circle circle = new Circle(); + Drawing drawing = new Drawing(); + + drawing.Add( rectangle ); + drawing.Add( circle ); + + for( int i = 0; i < drawing.Count; ++i ) { + GeometricShape shape = drawing[i]; + shape.Draw(); + } + } +} diff --git a/4_classes_structs/4_inheritance_1.cs b/4_classes_structs/4_inheritance_1.cs new file mode 100644 index 0000000..7c1d08e --- /dev/null +++ b/4_classes_structs/4_inheritance_1.cs @@ -0,0 +1,27 @@ +public class Base +{ + public void Base(); + + public void DoSomething() + { + // Doing something + } +} + +public interface ISomeInterface +{ + void DoSomethingElse(); +} + +public class Derived : Base, ISomeInterface +{ + public void DoSomethingElse() + { + // doing something else + } + + public void DoSomethingCompletelyDifferent() + { + // doing something completely different. + } +} diff --git a/4_classes_structs/4_inheritance_2.cs b/4_classes_structs/4_inheritance_2.cs new file mode 100644 index 0000000..d69cfca --- /dev/null +++ b/4_classes_structs/4_inheritance_2.cs @@ -0,0 +1,8 @@ +class A +{ + protected int x; +} + +public class B : A +{ +} diff --git a/4_classes_structs/4_inheritance_3.cs b/4_classes_structs/4_inheritance_3.cs new file mode 100644 index 0000000..ade9e5b --- /dev/null +++ b/4_classes_structs/4_inheritance_3.cs @@ -0,0 +1,26 @@ +public class A +{ + public void DoSomething() + { + System.Console.WriteLine( "A.DoSomething" ); + } +} + +public class B : A +{ + public void DoSomethingElse() + { + System.Console.WriteLine( "B.DoSomethingElse" ); + } +} + +public class EntryPoint +{ + static void Main() + { + B b = new B(); + + b.DoSomething(); + b.DoSomethingElse(); + } +} diff --git a/4_classes_structs/4_inheritance_4.cs b/4_classes_structs/4_inheritance_4.cs new file mode 100644 index 0000000..18e38d8 --- /dev/null +++ b/4_classes_structs/4_inheritance_4.cs @@ -0,0 +1,34 @@ +public class A +{ + public void DoSomething() + { + System.Console.WriteLine( "A.DoSomething" ); + } +} + +public class B : A +{ + public void DoSomethingElse() + { + System.Console.WriteLine( "B.DoSomethingElse" ); + } + + public new void DoSomething() + { + System.Console.WriteLine( "B.DoSomething" ); + } +} + +public class EntryPoint +{ + static void Main() + { + B b = new B(); + + b.DoSomething(); + b.DoSomethingElse(); + + A a = b; + a.DoSomething(); + } +} diff --git a/4_classes_structs/4_inheritance_5.cs b/4_classes_structs/4_inheritance_5.cs new file mode 100644 index 0000000..9292529 --- /dev/null +++ b/4_classes_structs/4_inheritance_5.cs @@ -0,0 +1,39 @@ +public class A +{ + public A( int var ) + { + this.x = var; + } + + public virtual void DoSomething() + { + System.Console.WriteLine( "A.DoSomething" ); + } + + private int x; +} + +public class B : A +{ + public B() + : base( 123 ) + { + } + + public override void DoSomething() + { + System.Console.WriteLine( "B.DoSomething" ); + base.DoSomething(); + } + +} + +public class EntryPoint +{ + static void Main() + { + B b = new B(); + + b.DoSomething(); + } +} diff --git a/4_classes_structs/4_inst_ctor_1.cs b/4_classes_structs/4_inst_ctor_1.cs new file mode 100644 index 0000000..a0963a0 --- /dev/null +++ b/4_classes_structs/4_inst_ctor_1.cs @@ -0,0 +1,59 @@ +using System; + +class Base +{ + public Base( int x ) + { + Console.WriteLine( "Base.Base(int)" ); + this.x = x; + } + + private static int InitX() + { + Console.WriteLine( "Base.InitX()" ); + return 1; + } + + public int x = InitX(); +} + +class Derived : Base +{ + public Derived( int a ) + :base( a ) + { + Console.WriteLine( "Derived.Derived(int)" ); + this.a = a; + } + + public Derived( int a, int b ) + :this( a ) + { + Console.WriteLine( "Derived.Derived(int, int)" ); + this.a = a; + this.b = b; + } + + private static int InitA() + { + Console.WriteLine( "Derived.InitA()" ); + return 3; + } + + private static int InitB() + { + Console.WriteLine( "Derived.InitB()" ); + return 4; + } + + public int a = InitA(); + public int b = InitB(); +} + +public class EntryPoint +{ + static void Main() + { + Derived b = new Derived( 1, 2 ); + } +} diff --git a/4_classes_structs/4_inst_ctor_2.cs b/4_classes_structs/4_inst_ctor_2.cs new file mode 100644 index 0000000..e09c890 --- /dev/null +++ b/4_classes_structs/4_inst_ctor_2.cs @@ -0,0 +1,38 @@ +using System; + +public class A +{ + public virtual void DoSomething() + { + Console.WriteLine( "A.DoSomething()" ); + } + + public A() + { + DoSomething(); + } +} + +public class B : A +{ + public override void DoSomething() + { + Console.WriteLine( "B.DoSomething()" ); + Console.WriteLine( "x = {0}", x ); + } + + public B() + :base() + { + } + + private int x = 123; +} + +public class EntryPoint +{ + static void Main() + { + B b = new B(); + } +} diff --git a/4_classes_structs/4_inst_init_1.cs b/4_classes_structs/4_inst_init_1.cs new file mode 100644 index 0000000..ba50ec2 --- /dev/null +++ b/4_classes_structs/4_inst_init_1.cs @@ -0,0 +1,20 @@ +public class A +{ + public A(int x) { + this.x = x; + } + + private int x; +} + +public class B : A +{ +} + +public class EntryPoint +{ + static void Main() + { + B b = new B(); + } +} diff --git a/4_classes_structs/4_instance_ctor_1.cs b/4_classes_structs/4_instance_ctor_1.cs new file mode 100644 index 0000000..fec943b --- /dev/null +++ b/4_classes_structs/4_instance_ctor_1.cs @@ -0,0 +1,33 @@ +public class A +{ + public A( int x ) + { + this.x = x; + } + + public A() : this( 123 ) + { + } + + internal int x; +} + +public class B : A +{ + public B() : base( 456 ) + { + } + + ~B() + { + } +} + +public class EntryPoint +{ + static void Main() + { + B b = new B(); + System.Console.WriteLine( "A.x = {0}", b.x ); + } +} diff --git a/4_classes_structs/4_instance_method_1.cs b/4_classes_structs/4_instance_method_1.cs new file mode 100644 index 0000000..59444d8 --- /dev/null +++ b/4_classes_structs/4_instance_method_1.cs @@ -0,0 +1,27 @@ +public class A +{ + private void SomeOperation() + { + x = 1; + this.y = 2; + z = 3; + + // assigning this in objects is an error. + // A newinstance = new A(); + // this = newinstance; + } + + private int x; + private int y; + private static int z; + + static void Main() + { + A obj = new A(); + + obj.SomeOperation(); + + System.Console.WriteLine( "x = {0}, y = {1}, z= {2}", + obj.x, obj.y, A.z ); + } +} diff --git a/4_classes_structs/4_interface_1.cs b/4_classes_structs/4_interface_1.cs new file mode 100644 index 0000000..c3966b5 --- /dev/null +++ b/4_classes_structs/4_interface_1.cs @@ -0,0 +1,23 @@ +public interface IMusician +{ + void PlayMusic(); +} + +public class TalentedPerson : IMusician +{ + void PlayMusic(); + void DoALittleDance(); +} + +public class EntryPoint +{ + static void Main() + { + TalentedPerson dude = new TalentedPerson(); + IMusician musician = dude; + + musician.PlayMusic(); + dude.PlayMusic(); + dude.DoALittleDance(); + } +} diff --git a/4_classes_structs/4_nested_classes_1.cs b/4_classes_structs/4_nested_classes_1.cs new file mode 100644 index 0000000..1275ee4 --- /dev/null +++ b/4_classes_structs/4_nested_classes_1.cs @@ -0,0 +1,94 @@ +using System.Collections; + +public abstract class GeometricShape +{ + public abstract void Draw(); +} + +public class Rectangle : GeometricShape +{ + public override void Draw() + { + System.Console.WriteLine( "Rectangle.Draw" ); + } +} + +public class Circle : GeometricShape +{ + public override void Draw() + { + System.Console.WriteLine( "Circle.Draw" ); + } +} + +public class Drawing : IEnumerable +{ + private ArrayList shapes; + + private class Iterator : IEnumerator + { + public Iterator( Drawing drawing ) + { + this.drawing = drawing; + this.current = -1; + } + + public void Reset() + { + current = -1; + } + + public bool MoveNext() + { + ++current; + if( current < drawing.shapes.Count ) { + return true; + } else { + return false; + } + } + + public object Current + { + get + { + return drawing.shapes[ current ]; + } + } + + private Drawing drawing; + private int current; + } + + public Drawing() + { + shapes = new ArrayList(); + } + + public IEnumerator GetEnumerator() + { + return new Iterator( this ); + } + + public void Add( GeometricShape shape ) + { + shapes.Add( shape ); + } +} + +public class EntryPoint +{ + static void Main() + { + Rectangle rectangle = new Rectangle(); + Circle circle = new Circle(); + Drawing drawing = new Drawing(); + + drawing.Add( rectangle ); + drawing.Add( circle ); + + foreach( GeometricShape shape in drawing ) { + shape.Draw(); + } + } +} diff --git a/4_classes_structs/4_nested_classes_2.cs b/4_classes_structs/4_nested_classes_2.cs new file mode 100644 index 0000000..4b3b6a2 --- /dev/null +++ b/4_classes_structs/4_nested_classes_2.cs @@ -0,0 +1,14 @@ +public class A +{ + public class B + { + } +} + +public class EntryPoint +{ + static void Main() + { + A.B b = new A.B(); + } +} diff --git a/4_classes_structs/4_nested_classes_3.cs b/4_classes_structs/4_nested_classes_3.cs new file mode 100644 index 0000000..51d23e5 --- /dev/null +++ b/4_classes_structs/4_nested_classes_3.cs @@ -0,0 +1,13 @@ +public class A +{ + public void Foo() + { + } +} + +public class B : A +{ + public new class Foo + { + } +} diff --git a/4_classes_structs/4_new_2.cs b/4_classes_structs/4_new_2.cs new file mode 100644 index 0000000..bab0c6a --- /dev/null +++ b/4_classes_structs/4_new_2.cs @@ -0,0 +1,24 @@ +public class MyClass +{ + public MyClass( int x, int y ) + { + this.x = x; + this.y = y; + } + + public int x; + public int y; +} + +public class EntryPoint +{ + static void Main() + { + // We can't do this! + // MyClass objA = new MyClass(); + + MyClass objA = new MyClass( 1, 2 ); + System.Console.WriteLine( "objA.x = {0}, objA.y = {1}", + objA.x, objA.y ); + } +} diff --git a/4_classes_structs/4_out_param_1.cs b/4_classes_structs/4_out_param_1.cs new file mode 100644 index 0000000..090c853 --- /dev/null +++ b/4_classes_structs/4_out_param_1.cs @@ -0,0 +1,11 @@ +public class EntryPoint +{ + static void Main() { + object obj; + PassAsOutParam( out obj ); + } + + static void PassAsOutParam( out object obj ) { + obj = new object(); + } +} diff --git a/4_classes_structs/4_override_1.cs b/4_classes_structs/4_override_1.cs new file mode 100644 index 0000000..ea486c2 --- /dev/null +++ b/4_classes_structs/4_override_1.cs @@ -0,0 +1,25 @@ +using System; + +public class A +{ + public virtual void SomeMethod() { + Console.WriteLine( "A::SomeMethod" ); + } +} + +public class B : A +{ + public void SomeMethod() { + Console.WriteLine( "B::SomeMethod" ); + } +} + +public class EntryPoint +{ + static void Main() { + B b = new B(); + A a = b; + + a.SomeMethod(); + } +} diff --git a/4_classes_structs/4_override_2.cs b/4_classes_structs/4_override_2.cs new file mode 100644 index 0000000..4956679 --- /dev/null +++ b/4_classes_structs/4_override_2.cs @@ -0,0 +1,27 @@ +using System; + +public class A +{ + public virtual void SomeMethod() { + Console.WriteLine( "A::SomeMethod" ); + } +} + +public class B : A +{ + public override void SomeMethod() { + Console.WriteLine( "B::SomeMethod" ); + base.SomeMethod(); + } +} + + +public class EntryPoint +{ + static void Main() { + B b = new B(); + A a = b; + + a.SomeMethod(); + } +} diff --git a/4_classes_structs/4_param_array_1.cs b/4_classes_structs/4_param_array_1.cs new file mode 100644 index 0000000..bc96702 --- /dev/null +++ b/4_classes_structs/4_param_array_1.cs @@ -0,0 +1,19 @@ +using System; + +public class EntryPoint +{ + static void Main() { + VarArgs( 42 ); + VarArgs( 42, 43, 44 ); + VarArgs( 44, 56, 23, 234, 45, 123 ); + } + + static void VarArgs( int val1, params int[] vals ) { + Console.WriteLine( "val1: {0}", val1 ); + foreach( int i in vals ) { + Console.WriteLine( "vals[]: {0}", + i ); + } + Console.WriteLine(); + } +} diff --git a/4_classes_structs/4_partial_methods_1a.cs b/4_classes_structs/4_partial_methods_1a.cs new file mode 100644 index 0000000..16bb9ff --- /dev/null +++ b/4_classes_structs/4_partial_methods_1a.cs @@ -0,0 +1,7 @@ +public partial class DataSource +{ + // Some useful methods + // ... + + partial void ResetSource(); +} diff --git a/4_classes_structs/4_partial_methods_1b.cs b/4_classes_structs/4_partial_methods_1b.cs new file mode 100644 index 0000000..e95367c --- /dev/null +++ b/4_classes_structs/4_partial_methods_1b.cs @@ -0,0 +1,21 @@ +using System; + +public partial class DataSource +{ + partial void ResetSource() { + Console.WriteLine( "Source was reset" ); + } + + public void Reset() { + ResetSource(); + } +} + +public class PartialMethods +{ + static void Main() { + DataSource ds = new DataSource(); + + ds.Reset(); + } +} diff --git a/4_classes_structs/4_properties_1.cs b/4_classes_structs/4_properties_1.cs new file mode 100644 index 0000000..f2a80ad --- /dev/null +++ b/4_classes_structs/4_properties_1.cs @@ -0,0 +1,18 @@ +public class A +{ + public static void SomeFunction( ref int i ) + { + i = 4; + } + + static void Main() + { + SomeObject obj = new SomeObject(); + + obj.X = 1; // could be a public field or a property + obj.Y = 2; // could be a public field or a property + + // This is an error if X is a property + // SomeFunction( ref obj.X ); + } +} diff --git a/4_classes_structs/4_properties_2.cs b/4_classes_structs/4_properties_2.cs new file mode 100644 index 0000000..a78c62a --- /dev/null +++ b/4_classes_structs/4_properties_2.cs @@ -0,0 +1,31 @@ +public class A +{ + private int temperature; + + public int Temperature + { + get + { + System.Console.WriteLine( "Getting value for temperature" ); + return temperature; + } + + set + { + System.Console.WriteLine( "Setting value for temperature" ); + temperature = value; + } + } +} + +public class MainClass +{ + static void Main() + { + A obj = new A(); + + obj.Temperature = 1; + System.Console.WriteLine( "obj.Temperature = {0}", + obj.Temperature ); + } +} diff --git a/4_classes_structs/4_properties_3.cs b/4_classes_structs/4_properties_3.cs new file mode 100644 index 0000000..2485cdc --- /dev/null +++ b/4_classes_structs/4_properties_3.cs @@ -0,0 +1,14 @@ +using System; + +public class Employee +{ + public string FullName { get; set; } + public string Id { get; set; } +} + +public class AutoProps +{ + static void Main() { + Employee emp = new Employee(); + } +} diff --git a/4_classes_structs/4_properties_4.cs b/4_classes_structs/4_properties_4.cs new file mode 100644 index 0000000..e9c64f9 --- /dev/null +++ b/4_classes_structs/4_properties_4.cs @@ -0,0 +1,17 @@ +using System; + +public class Employee +{ + public string FullName { get; private set; } + public string Id { get; set; } +} + +public class AutoProps +{ + static void Main() { + Employee emp = new Employee { + FullName = "John Doe", + Id = "111-11-1111" + }; + } +} diff --git a/4_classes_structs/4_readonly_1.cs b/4_classes_structs/4_readonly_1.cs new file mode 100644 index 0000000..e4598b0 --- /dev/null +++ b/4_classes_structs/4_readonly_1.cs @@ -0,0 +1,30 @@ +public class A +{ + public A() + { + this.y = 456; + + // We can even set y again. + this.y = 654; + + // We can use y as a ref param. + SetField( ref this.y ); + } + + private void SetField( ref int val ) + { + val = 888; + } + + private readonly int x = 123; + private readonly int y; + public const int z = 555; + + static void Main() + { + A obj = new A(); + + System.Console.WriteLine( "x = {0}, y = {1}, z = {2}", + obj.x, obj.y, A.z ); + } +} diff --git a/4_classes_structs/4_ref_param_1.cs b/4_classes_structs/4_ref_param_1.cs new file mode 100644 index 0000000..245aabd --- /dev/null +++ b/4_classes_structs/4_ref_param_1.cs @@ -0,0 +1,30 @@ +using System; + +public struct MyStruct +{ + public int val; +} + +public class EntryPoint +{ + static void Main() { + MyStruct myValue = new MyStruct(); + myValue.val = 10; + + PassByValue( myValue ); + Console.WriteLine( "Result of PassByValue: myValue.val = {0}", + myValue.val ); + + PassByRef( ref myValue ); + Console.WriteLine( "Result of PassByRef: myValue.val = {0}", + myValue.val ); + } + + static void PassByValue( MyStruct myValue ) { + myValue.val = 50; + } + + static void PassByRef( ref MyStruct myValue ) { + myValue.val = 42; + } +} diff --git a/4_classes_structs/4_ref_param_2.cs b/4_classes_structs/4_ref_param_2.cs new file mode 100644 index 0000000..97683bc --- /dev/null +++ b/4_classes_structs/4_ref_param_2.cs @@ -0,0 +1,19 @@ +using System; + +public class EntryPoint +{ + static void Main() { + object myObject = new Object(); + + Console.WriteLine( "myObject.GetHashCode() == {0}", + myObject.GetHashCode() ); + PassByRef( ref myObject ); + Console.WriteLine( "myObject.GetHashCode() == {0}", + myObject.GetHashCode() ); + } + + static void PassByRef( ref object myObject ) { + // Assign a new instance to the variable. + myObject = new Object(); + } +} diff --git a/4_classes_structs/4_specialization_1.cs b/4_classes_structs/4_specialization_1.cs new file mode 100644 index 0000000..1248cdd --- /dev/null +++ b/4_classes_structs/4_specialization_1.cs @@ -0,0 +1,40 @@ +public class GeometricShape +{ + public virtual void Draw() + { + // Do some default drawing stuff. + } +} + +public class Rectangle : GeometricShape +{ + public override void Draw() + { + // Draw a rectangle + } +} + +public class Circle : GeometricShape +{ + public override void Draw() + { + // Draw a circle + } +} + +public class EntryPoint +{ + private static void DrawShape( GeometricShape shape ) + { + shape.Draw(); + } + + static void Main() + { + Circle circle = new Circle(); + GeometricShape shape = circle; + + DrawShape( shape ); + DrawShape( circle ); + } +} diff --git a/4_classes_structs/4_static_class_1.cs b/4_classes_structs/4_static_class_1.cs new file mode 100644 index 0000000..79ed9d8 --- /dev/null +++ b/4_classes_structs/4_static_class_1.cs @@ -0,0 +1,38 @@ +using System; + +public static class StaticClass +{ + public static void DoWork() { + ++callCount; + Console.WriteLine( "StaticClass.DoWork()" ); + } + + public class NestedClass { + public NestedClass() { + Console.WriteLine( "NestedClass.NestedClass()" ); + } + } + + private static long callCount = 0; + public static long CallCount { + get { + return callCount; + } + } +} + +public static class EntryPoint +{ + static void Main() { + StaticClass.DoWork(); + + // OOPS! Cannot do this! + // StaticClass obj = new StaticClass(); + + StaticClass.NestedClass nested = + new StaticClass.NestedClass(); + + Console.WriteLine( "CallCount = {0}", + StaticClass.CallCount ); + } +} diff --git a/4_classes_structs/4_static_ctor_1.cs b/4_classes_structs/4_static_ctor_1.cs new file mode 100644 index 0000000..bd8a4fd --- /dev/null +++ b/4_classes_structs/4_static_ctor_1.cs @@ -0,0 +1,44 @@ +using System; + +public class A +{ + static A() + { + Console.WriteLine( "static A::A()" ); + } + + private static int InitX() + { + Console.WriteLine( "A.InitX()" ); + return 1; + } + private static int InitY() + { + Console.WriteLine( "A.InitY()" ); + return 2; + } + private static int InitA() + { + Console.WriteLine( "A.InitA()" ); + return 3; + } + private static int InitB() + { + Console.WriteLine( "A.InitB()" ); + return 4; + } + + private int y = InitY(); + private int x = InitX(); + + private static int a = InitA(); + private static int b = InitB(); +} + +public class EntryPoint +{ + static void Main() + { + A a = new A(); + } +} diff --git a/4_classes_structs/4_static_field_example_1.cs b/4_classes_structs/4_static_field_example_1.cs new file mode 100644 index 0000000..fe733ef --- /dev/null +++ b/4_classes_structs/4_static_field_example_1.cs @@ -0,0 +1,33 @@ +public class Employee +{ + public Employee() + { + // Set the static field to something. + totalHeadCount = 123; + + // The following is a compiler error !! + // this.totalHeadCount = 123; + + // Set the static field to something else. + Employee.totalHeadCount = 456; + } + + public static int totalHeadCount; +} + +public class EntryPoint +{ + static void Main() + { + Employee bob = new Employee(); + + System.Console.WriteLine( + "Static Field Employee.totalHeadCount is {0}", + Employee.totalHeadCount ); + + // The following is a compile error !! + // System.Console.WriteLine( + // "Static Field Employee.totalHeadCount is {0}", + // bob.totalHeadCount ); + } +} diff --git a/4_classes_structs/4_static_method_1.cs b/4_classes_structs/4_static_method_1.cs new file mode 100644 index 0000000..162c60d --- /dev/null +++ b/4_classes_structs/4_static_method_1.cs @@ -0,0 +1,13 @@ +public class A +{ + public static void SomeFunction() + { + System.Console.WriteLine( "SomeFunction() called" ); + } + + static void Main() + { + A.SomeFunction(); + SomeFunction(); + } +} diff --git a/4_classes_structs/4_struct_this_1.cs b/4_classes_structs/4_struct_this_1.cs new file mode 100644 index 0000000..cd65913 --- /dev/null +++ b/4_classes_structs/4_struct_this_1.cs @@ -0,0 +1,25 @@ +public struct ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + public ComplexNumber( ComplexNumber other ) + { + this = other; + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() + { + ComplexNumber valA = new ComplexNumber( 1, 2 ); + ComplexNumber copyA = new ComplexNumber( valA ); + } +} diff --git a/4_classes_structs/4_struct_this_2.cs b/4_classes_structs/4_struct_this_2.cs new file mode 100644 index 0000000..a5f5783 --- /dev/null +++ b/4_classes_structs/4_struct_this_2.cs @@ -0,0 +1,16 @@ +public struct ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + public ComplexNumber( double real ) + { + this.real = real; + } + + private double real; + private double imaginary; +} diff --git a/4_classes_structs/4_struct_this_3.cs b/4_classes_structs/4_struct_this_3.cs new file mode 100644 index 0000000..0e6348e --- /dev/null +++ b/4_classes_structs/4_struct_this_3.cs @@ -0,0 +1,25 @@ +public struct ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + public ComplexNumber( double real ) + :this( real, 0 ) + { + this.real = real; + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() + { + ComplexNumber valA = new ComplexNumber( 1, 2 ); + } +} diff --git a/4_classes_structs/4_struct_this_4.cs b/4_classes_structs/4_struct_this_4.cs new file mode 100644 index 0000000..ab8601a --- /dev/null +++ b/4_classes_structs/4_struct_this_4.cs @@ -0,0 +1,17 @@ +public struct ComplexNumber +{ + public ComplexNumber( double real, double imaginary ) + { + this.real = real; + this.imaginary = imaginary; + } + + public ComplexNumber( double real ) + :this() + { + this.real = real; + } + + private double real; + private double imaginary; +} diff --git a/4_classes_structs/4_types_vs_class.cs b/4_classes_structs/4_types_vs_class.cs new file mode 100644 index 0000000..38f8650 --- /dev/null +++ b/4_classes_structs/4_types_vs_class.cs @@ -0,0 +1,28 @@ +interface IKnowsIcelandic +{ +} + +class Dog : IKnowsIcelandic +{ +} + +class Human : IKnowsIcelandic +{ +} + +class LanguagesAreFun +{ + static void ListenToMe( IKnowsIcelandic listener ) + { + } + + static void Main() + { + Dog dog = new Dog(); + Human human = new Human(); + + ListenToMe( dog ); + ListenToMe( human ); + } +} + diff --git a/4_classes_structs/anonymous_types_1.cs b/4_classes_structs/anonymous_types_1.cs new file mode 100644 index 0000000..65bdb96 --- /dev/null +++ b/4_classes_structs/anonymous_types_1.cs @@ -0,0 +1,18 @@ +using System; + +public class EntryPoint +{ + static void Main() { + var employeeInfo = new { Name = "Joe", Id = 42 }; + var customerInfo = new { Name = "Jane", Id = "AB123" }; + + Console.WriteLine( "Name: {0}, Id: {1}", + employeeInfo.Name, + employeeInfo.Id ); + + Console.WriteLine( "employeeInfo Type is actually: {0}", + employeeInfo.GetType() ); + Console.WriteLine( "customerInfo Type is actually: {0}", + customerInfo.GetType() ); + } +} diff --git a/4_classes_structs/anonymous_types_2.cs b/4_classes_structs/anonymous_types_2.cs new file mode 100644 index 0000000..0fe4b79 --- /dev/null +++ b/4_classes_structs/anonymous_types_2.cs @@ -0,0 +1,58 @@ +using System; + +public class ConventionalEmployeeInfo +{ + public ConventionalEmployeeInfo( string Name, int Id ) { + this.name = Name; + this.id = Id; + } + + public string Name { + get { + return name; + } + + set { + name = value; + } + } + + public int Id { + get { + return id; + } + + set { + id = value; + } + } + + private string name; + private int id; +} + +public class EntryPoint +{ + static void Main() { + ConventionalEmployeeInfo oldEmployee = + new ConventionalEmployeeInfo( "Joe", 42 ); + + var employeeInfo = new { oldEmployee.Name, + oldEmployee.Id }; + + string Name = "Jane"; + int Id = 1234; + + var customerInfo = new { Name, Id }; + + Console.WriteLine( "employeeInfo Name: {0}, Id: {1}", + employeeInfo.Name, + employeeInfo.Id ); + Console.WriteLine( "customerInfo Name: {0}, Id: {1}", + customerInfo.Name, + customerInfo.Id ); + + Console.WriteLine( "Anonymous Type is actually: {0}", + employeeInfo.GetType() ); + } +} diff --git a/4_classes_structs/obj_initializer_1.cs b/4_classes_structs/obj_initializer_1.cs new file mode 100644 index 0000000..145ddb0 --- /dev/null +++ b/4_classes_structs/obj_initializer_1.cs @@ -0,0 +1,22 @@ +using System; + +public class Employee +{ + public string Name { + get; set; + } + + public string OfficeLocation { + get; set; + } +} + +public class InitExample +{ + static void Main() { + Employee developer = new Employee { + Name = "Fred Blaze", + OfficeLocation = "B1" + }; + } +} diff --git a/4_classes_structs/obj_initializer_2.cs b/4_classes_structs/obj_initializer_2.cs new file mode 100644 index 0000000..889ec6d --- /dev/null +++ b/4_classes_structs/obj_initializer_2.cs @@ -0,0 +1,29 @@ +using System; + +public class Employee +{ + public string Name { get; set; } + public string OfficeLocation { get; set; } +} + +public class FeatureDevPair +{ + public Employee Developer { get; set; } + public Employee QaEngineer { get; set; } +} + +public class InitExample +{ + static void Main() { + FeatureDevPair spellCheckerTeam = new FeatureDevPair { + Developer = new Employee { + Name = "Fred Blaze", + OfficeLocation = "B1" + }, + QaEngineer = new Employee { + Name = "Marisa Bozza", + OfficeLocation = "L42" + } + }; + } +} diff --git a/4_classes_structs/obj_initializer_3.cs b/4_classes_structs/obj_initializer_3.cs new file mode 100644 index 0000000..ee0bdc8 --- /dev/null +++ b/4_classes_structs/obj_initializer_3.cs @@ -0,0 +1,39 @@ +using System; + +public class Employee +{ + public string Name { get; set; } + public string OfficeLocation { get; set; } +} + +public class FeatureDevPair +{ + private Employee developer = new Employee(); + private Employee qaEngineer = new Employee(); + + public Employee Developer { + get { return developer; } + set { developer = value; } + } + + public Employee QaEngineer { + get { return qaEngineer; } + set { qaEngineer = value; } + } +} + +public class InitExample +{ + static void Main() { + FeatureDevPair spellCheckerTeam = new FeatureDevPair { + Developer = { + Name = "Fred Blaze", + OfficeLocation = "B1" + }, + QaEngineer = { + Name = "Marisa Bozza", + OfficeLocation = "L42" + } + }; + } +} diff --git a/5_interfaces/abstract_1.cs b/5_interfaces/abstract_1.cs new file mode 100644 index 0000000..d24aafc --- /dev/null +++ b/5_interfaces/abstract_1.cs @@ -0,0 +1,21 @@ +public abstract class MyOperations +{ + public virtual void Operation1() { + } + + public virtual void Operation2() { + } +} + +// Client class +public class ClientClass : MyOperations +{ + public override void Operation1() { } + public override void Operation2() { } +} + +public class AnotherClass +{ + public void DoWork( MyOperations ops ) { + } +} diff --git a/5_interfaces/abstract_2.cs b/5_interfaces/abstract_2.cs new file mode 100644 index 0000000..20ac262 --- /dev/null +++ b/5_interfaces/abstract_2.cs @@ -0,0 +1,26 @@ +public abstract class MyOperations +{ + public virtual void Operation1() { + } + + public virtual void Operation2() { + } + + public virtual void Operation3() { + // New default implementation + } +} + +// Client class +public class ClientClass : MyOperations +{ + public override void Operation1() { } + public override void Operation2() { } +} + +public class AnotherClass +{ + public void DoWork( MyOperations ops ) { + ops.Operation3(); + } +} diff --git a/5_interfaces/crazy_1.cs b/5_interfaces/crazy_1.cs new file mode 100644 index 0000000..0cdaa0f --- /dev/null +++ b/5_interfaces/crazy_1.cs @@ -0,0 +1,39 @@ +using System; + +public interface I +{ + void Go(); +} + +public class A : I +{ + public void Go() { + Console.WriteLine( "A.Go()" ); + } +} + +public class B : A +{ +} + +public class C : B, I +{ + public new void Go() { + Console.WriteLine( "C.Go()" ); + } +} + +public class EntryPoint +{ + static void Main() { + B b1 = new B(); + + C c1 = new C(); + B b2 = c1; + + b1.Go(); + c1.Go(); + b2.Go(); + ((I)b2).Go(); + } +} diff --git a/5_interfaces/diamond_1.cs b/5_interfaces/diamond_1.cs new file mode 100644 index 0000000..ec21180 --- /dev/null +++ b/5_interfaces/diamond_1.cs @@ -0,0 +1,19 @@ +public interface IUIControl +{ + void Paint(); +} + +public interface IEditBox : IUIControl +{ +} + +public interface IDropList : IUIControl +{ +} + +public class ComboBox : IEditBox, IDropList +{ + public void Paint() { + // paint implementation for ComboBox + } +} diff --git a/5_interfaces/diamond_2.cs b/5_interfaces/diamond_2.cs new file mode 100644 index 0000000..5809f6d --- /dev/null +++ b/5_interfaces/diamond_2.cs @@ -0,0 +1,33 @@ +using System; + +public interface IUIControl +{ + void Paint(); +} + +public interface IEditBox : IUIControl +{ + new void Paint(); +} + +public interface IDropList : IUIControl +{ +} + +public class ComboBox : IEditBox, IDropList +{ + public void Paint() { + Console.WriteLine( "ComboBox.IEditBox.Paint()" ); + } +} + +public class EntryPoint +{ + static void Main() { + ComboBox cb = new ComboBox(); + cb.Paint(); + ((IEditBox)cb).Paint(); + ((IDropList)cb).Paint(); + ((IUIControl)cb).Paint(); + } +} diff --git a/5_interfaces/diamond_3.cs b/5_interfaces/diamond_3.cs new file mode 100644 index 0000000..434827e --- /dev/null +++ b/5_interfaces/diamond_3.cs @@ -0,0 +1,41 @@ +using System; + +public interface IUIControl +{ + void Paint(); +} + +public interface IEditBox : IUIControl +{ + new void Paint(); +} + +public interface IDropList : IUIControl +{ +} + +public class ComboBox : IEditBox, IDropList +{ + void IEditBox.Paint() { + Console.WriteLine( "ComboBox.IEditBox.Paint()" ); + } + + void IUIControl.Paint() { + Console.WriteLine( "ComboBox.IUIControl.Paint()" ); + } + + public void Paint() { + ((IUIControl)this).Paint(); + } +} + +public class EntryPoint +{ + static void Main() { + ComboBox cb = new ComboBox(); + cb.Paint(); + ((IEditBox)cb).Paint(); + ((IDropList)cb).Paint(); + ((IUIControl)cb).Paint(); + } +} diff --git a/5_interfaces/diamond_4.cs b/5_interfaces/diamond_4.cs new file mode 100644 index 0000000..fddb2f4 --- /dev/null +++ b/5_interfaces/diamond_4.cs @@ -0,0 +1,39 @@ +using System; + +public interface IUIControl +{ + void Paint(); + void Show(); +} + +public interface IEditBox : IUIControl +{ + void SelectText(); +} + +public interface IDropList : IUIControl +{ + void ShowList(); +} + +public class ComboBox : IEditBox, IDropList +{ + public void Paint() { } + public void Show() { } + + public void SelectText() { } + + public void ShowList() { } +} + +public class FancyComboBox : ComboBox +{ + public void Paint() { } +} + +public class EntryPoint +{ + static void Main() { + FancyComboBox cb = new FancyComboBox(); + } +} diff --git a/5_interfaces/diamond_5.cs b/5_interfaces/diamond_5.cs new file mode 100644 index 0000000..d3502cb --- /dev/null +++ b/5_interfaces/diamond_5.cs @@ -0,0 +1,46 @@ +using System; + +public interface IUIControl +{ + void Paint(); + void Show(); +} + +public interface IEditBox : IUIControl +{ + void SelectText(); +} + +public interface IDropList : IUIControl +{ + void ShowList(); +} + +public class ComboBox : IEditBox, IDropList +{ + public void Paint() { + Console.WriteLine( "ComboBox.Paint()" ); + } + public void Show() { } + + public void SelectText() { } + + public void ShowList() { } +} + +public class FancyComboBox : ComboBox, IUIControl +{ + public new void Paint() { + Console.WriteLine( "FancyComboBox.Paint()" ); + } +} + +public class EntryPoint +{ + static void Main() { + FancyComboBox cb = new FancyComboBox(); + cb.Paint(); + ((IUIControl)cb).Paint(); + ((IEditBox)cb).Paint(); + } +} diff --git a/5_interfaces/diamond_6.cs b/5_interfaces/diamond_6.cs new file mode 100644 index 0000000..f684c0c --- /dev/null +++ b/5_interfaces/diamond_6.cs @@ -0,0 +1,46 @@ +using System; + +public interface IUIControl +{ + void Paint(); + void Show(); +} + +public interface IEditBox : IUIControl +{ + void SelectText(); +} + +public interface IDropList : IUIControl +{ + void ShowList(); +} + +public class ComboBox : IEditBox, IDropList +{ + public virtual void Paint() { + Console.WriteLine( "ComboBox.Paint()" ); + } + public void Show() { } + + public void SelectText() { } + + public void ShowList() { } +} + +public class FancyComboBox : ComboBox +{ + public override void Paint() { + Console.WriteLine( "FancyComboBox.Paint()" ); + } +} + +public class EntryPoint +{ + static void Main() { + FancyComboBox cb = new FancyComboBox(); + cb.Paint(); + ((IUIControl)cb).Paint(); + ((IEditBox)cb).Paint(); + } +} diff --git a/5_interfaces/iface_1.cs b/5_interfaces/iface_1.cs new file mode 100644 index 0000000..4e715d0 --- /dev/null +++ b/5_interfaces/iface_1.cs @@ -0,0 +1,12 @@ +public interface IMyOperations +{ + void Operation1(); + void Operation2(); +} + +// Client class +public class ClientClass : IMyOperations +{ + public void Operation1() { } + public void Operation2() { } +} diff --git a/5_interfaces/iface_2.cs b/5_interfaces/iface_2.cs new file mode 100644 index 0000000..489499e --- /dev/null +++ b/5_interfaces/iface_2.cs @@ -0,0 +1,27 @@ +public interface IMyOperations +{ + void Operation1(); + void Operation2(); +} + +public interface IMyOperations2 +{ + void Operation1(); + void Operation2(); + void Operation3(); +} + +// Client class +public class ClientClass : IMyOperations, + IMyOperations2 +{ + public void Operation1() { } + public void Operation2() { } + public void Operation3() { } +} + +public class AnotherClass +{ + public void DoWork( IMyOperations ops ) { + } +} diff --git a/5_interfaces/method_search_1.cs b/5_interfaces/method_search_1.cs new file mode 100644 index 0000000..1d88cb4 --- /dev/null +++ b/5_interfaces/method_search_1.cs @@ -0,0 +1,46 @@ +using System; + +public interface ISomeInterface +{ + void SomeMethod(); +} + +public interface IAnotherInterface : ISomeInterface +{ + void AnotherMethod(); +} + +public class SomeClass : IAnotherInterface +{ + public void SomeMethod() { + Console.WriteLine( "SomeClass.SomeMethod()" ); + } + + public virtual void AnotherMethod() { + Console.WriteLine( "SomeClass.AnotherMethod()" ); + } +} + +public class SomeDerivedClass : SomeClass +{ + public new void SomeMethod() { + Console.WriteLine( "SomeDerivedClass.SomeMethod()" ); + } + + public override void AnotherMethod() { + Console.WriteLine( "SomeDerivedClass.AnotherMethod()" ); + } +} + +public class EntryPoint +{ + static void Main() { + SomeDerivedClass obj = new SomeDerivedClass(); + ISomeInterface isi = obj; + IAnotherInterface iai = obj; + + isi.SomeMethod(); + iai.SomeMethod(); + iai.AnotherMethod(); + } +} diff --git a/5_interfaces/value_type_1.cs b/5_interfaces/value_type_1.cs new file mode 100644 index 0000000..f045522 --- /dev/null +++ b/5_interfaces/value_type_1.cs @@ -0,0 +1,30 @@ +using System; + +public struct SomeValue : IComparable +{ + public SomeValue( int n ) { + this.n = n; + } + + public int CompareTo( object obj ) { + if( obj is SomeValue ) { + SomeValue other = (SomeValue) obj; + + return n - other.n; + } else { + throw new ArgumentException( "Wrong Type!" ); + } + } + + private int n; +} + +public class EntryPoint +{ + static void Main() { + SomeValue val1 = new SomeValue( 1 ); + SomeValue val2 = new SomeValue( 2 ); + + Console.WriteLine( val1.CompareTo(val2) ); + } +} diff --git a/5_interfaces/value_type_2.cs b/5_interfaces/value_type_2.cs new file mode 100644 index 0000000..f850e9e --- /dev/null +++ b/5_interfaces/value_type_2.cs @@ -0,0 +1,34 @@ +using System; + +public struct SomeValue : IComparable +{ + public SomeValue( int n ) { + this.n = n; + } + + int IComparable.CompareTo( object obj ) { + if( obj is SomeValue ) { + SomeValue other = (SomeValue) obj; + + return n - other.n; + } else { + throw new ArgumentException( "Wrong Type!" ); + } + } + + public int CompareTo( SomeValue other ) { + return n - other.n; + } + + private int n; +} + +public class EntryPoint +{ + static void Main() { + SomeValue val1 = new SomeValue( 1 ); + SomeValue val2 = new SomeValue( 2 ); + + Console.WriteLine( val1.CompareTo(val2) ); + } +} diff --git a/5_interfaces/zoo_1.cs b/5_interfaces/zoo_1.cs new file mode 100644 index 0000000..efb6f52 --- /dev/null +++ b/5_interfaces/zoo_1.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.ObjectModel; + +namespace CityOfShanoo.MyZoo +{ + +public struct Point +{ + public double X; + public double Y; +} + +public abstract class ZooDweller +{ + public void EatSomeFood() { + DoEatTheFood(); + } + + protected abstract void DoEatTheFood(); +} + +public sealed class ZooKeeper +{ + public void SendFlyCommand( Point to ) { + // Implementation removed for clarity. + } +} + +public sealed class Zoo +{ + private static Zoo theInstance = new Zoo(); + public static Zoo GetInstance() { + return theInstance; + } + + private Zoo() { + creatures = new Collection(); + zooKeeper = new ZooKeeper(); + } + + public ZooKeeper ZooKeeper { + get { + return zooKeeper; + } + } + + private ZooKeeper zooKeeper; + private Collection creatures; +} + +} diff --git a/5_interfaces/zoo_2.cs b/5_interfaces/zoo_2.cs new file mode 100644 index 0000000..c4abe97 --- /dev/null +++ b/5_interfaces/zoo_2.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.ObjectModel; + +namespace CityOfShanoo.MyZoo +{ + +public struct Point +{ + public double x; + public double y; +} + +public interface IFly +{ + void FlyTo( Point destination ); +} + +public abstract class ZooDweller +{ + public void EatSomeFood() { + DoEatTheFood(); + } + + protected abstract void DoEatTheFood(); +} + +public class Bird : ZooDweller, IFly +{ + public void FlyTo( Point destination ) { + Console.WriteLine( "Flying to ({0}. {1}).", + destination ); + } + + protected override void DoEatTheFood() { + Console.WriteLine( "Eating some food." ); + } +} + +public sealed class ZooKeeper +{ + public void SendFlyCommand( Point to ) { + } +} + +public sealed class Zoo +{ + private static Zoo theInstance = new Zoo(); + public static Zoo GetInstance() { + return theInstance; + } + + private Zoo() { + creatures = new Collection(); + zooKeeper = new ZooKeeper(); + } + + public ZooKeeper ZooKeeper { + get { + return zooKeeper; + } + } + + private ZooKeeper zooKeeper; + private Collection creatures; +} + +} diff --git a/6_operators/6_complex_1.cs b/6_operators/6_complex_1.cs new file mode 100644 index 0000000..a60bfef --- /dev/null +++ b/6_operators/6_complex_1.cs @@ -0,0 +1,64 @@ +using System; + +public struct Complex +{ + public Complex( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + static public Complex Add( Complex lhs, + Complex rhs ) { + return new Complex( lhs.real + rhs.real, + lhs.imaginary + rhs.imaginary ); + } + + static public Complex Add( Complex lhs, + double rhs ) { + + return new Complex( rhs + lhs.real, + lhs.imaginary ); + } + + public override string ToString() { + return String.Format( "({0}, {1})", + real, + imaginary ); + } + + static public Complex operator+( Complex lhs, + Complex rhs ) { + return Add( lhs, rhs ); + } + + static public Complex operator+( double lhs, + Complex rhs ) { + return Add( rhs, lhs ); + } + + static public Complex operator+( Complex lhs, + double rhs ) { + return Add( lhs, rhs ); + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() { + Complex cpx1 = new Complex( 1.0, 3.0 ); + Complex cpx2 = new Complex( 1.0, 2.0 ); + + Complex cpx3 = cpx1 + cpx2; + Complex cpx4 = 20.0 + cpx1; + Complex cpx5 = cpx1 + 25.0; + + Console.WriteLine( "cpx1 == {0}", cpx1 ); + Console.WriteLine( "cpx2 == {0}", cpx2 ); + Console.WriteLine( "cpx3 == {0}", cpx3 ); + Console.WriteLine( "cpx4 == {0}", cpx4 ); + Console.WriteLine( "cpx5 == {0}", cpx5 ); + } +} diff --git a/6_operators/6_complex_2.cs b/6_operators/6_complex_2.cs new file mode 100644 index 0000000..f147ef6 --- /dev/null +++ b/6_operators/6_complex_2.cs @@ -0,0 +1,117 @@ +using System; + +public struct Complex : IComparable, + IEquatable, + IComparable +{ + public Complex( double real, double img ) { + this.real = real; + this.img = img; + } + + // System.Object override + public override bool Equals( object other ) { + bool result = false; + if( other is Complex ) { + result = Equals( (Complex) other ); + } + return result; + } + + // Typesafe version + public bool Equals( Complex that ) { + return (this.real == that.real && + this.img == that.img); + } + + // Must override this if overriding Object.Equals() + public override int GetHashCode() { + return (int) this.Magnitude; + } + + // Typesafe version + public int CompareTo( Complex that ) { + int result; + if( Equals( that ) ) { + result = 0; + } else if( this.Magnitude > that.Magnitude ) { + result = 1; + } else { + result = -1; + } + + return result; + } + + // IComparable implementation + int IComparable.CompareTo( object other ) { + if( !(other is Complex) ) { + throw new ArgumentException( "Bad Comparison" ); + } + + return CompareTo( (Complex) other ); + } + + // System.Object override + public override string ToString() { + return String.Format( "({0}, {1})", + real, + img ); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.img, 2) ); + } + } + + // Overloaded operators + public static bool operator==( Complex lhs, Complex rhs ) { + return lhs.Equals( rhs ); + } + + public static bool operator!=( Complex lhs, Complex rhs ) { + return !lhs.Equals( rhs ); + } + + public static bool operator<( Complex lhs, Complex rhs ) { + return lhs.CompareTo( rhs ) < 0; + } + + public static bool operator>( Complex lhs, Complex rhs ) { + return lhs.CompareTo( rhs ) > 0; + } + + public static bool operator<=( Complex lhs, Complex rhs ) { + return lhs.CompareTo( rhs ) <= 0; + } + + public static bool operator>=( Complex lhs, Complex rhs ) { + return lhs.CompareTo( rhs ) >= 0; + } + + // Other methods ommitted for clarity. + + private double real; + private double img; +} + +public class EntryPoint +{ + static void Main() { + Complex cpx1 = new Complex( 1.0, 3.0 ); + Complex cpx2 = new Complex( 1.0, 2.0 ); + + Console.WriteLine( "cpx1 = {0}, cpx1.Magnitude = {1}", + cpx1, cpx1.Magnitude ); + Console.WriteLine( "cpx2 = {0}, cpx2.Magnitude = {1}\n", + cpx2, cpx2.Magnitude ); + Console.WriteLine( "cpx1 == cpx2 ? {0}", cpx1 == cpx2 ); + Console.WriteLine( "cpx1 != cpx2 ? {0}", cpx1 != cpx2 ); + Console.WriteLine( "cpx1 < cpx2 ? {0}", cpx1 < cpx2 ); + Console.WriteLine( "cpx1 > cpx2 ? {0}", cpx1 > cpx2 ); + Console.WriteLine( "cpx1 <= cpx2 ? {0}", cpx1 <= cpx2 ); + Console.WriteLine( "cpx1 >= cpx2 ? {0}", cpx1 >= cpx2 ); + } +} diff --git a/6_operators/6_complex_3.cs b/6_operators/6_complex_3.cs new file mode 100644 index 0000000..27af903 --- /dev/null +++ b/6_operators/6_complex_3.cs @@ -0,0 +1,48 @@ +using System; + +public struct Complex +{ + public Complex( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + // System.Object override + public override string ToString() { + return String.Format( "({0}, {1})", real, imaginary ); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + public static implicit operator Complex( double d ) { + return new Complex( d, 0 ); + } + + public static explicit operator double( Complex c ) { + return c.Magnitude; + } + + // Other methods ommitted for clarity. + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() { + Complex cpx1 = new Complex( 1.0, 3.0 ); + Complex cpx2 = 2.0; // Use implicit operator. + + double d = (double) cpx1; // Use explicit operator. + + Console.WriteLine( "cpx1 = {0}", cpx1 ); + Console.WriteLine( "cpx2 = {0}", cpx2 ); + Console.WriteLine( "d = {0}", d ); + } +} diff --git a/6_operators/6_complex_4.cs b/6_operators/6_complex_4.cs new file mode 100644 index 0000000..c689c2b --- /dev/null +++ b/6_operators/6_complex_4.cs @@ -0,0 +1,51 @@ +using System; + +public struct Complex +{ + public Complex( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + // System.Object override + public override string ToString() { + return String.Format( "({0}, {1})", + real, + imaginary ); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + public static bool operator true( Complex c ) { + return (c.real != 0) || (c.imaginary != 0); + } + + public static bool operator false( Complex c ) { + return (c.real == 0) && (c.imaginary == 0); + } + + // Other methods ommitted for clarity. + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() { + Complex cpx1 = new Complex( 1.0, 3.0 ); + if( cpx1 ) { + Console.WriteLine( "cpx1 is true" ); + } else { + Console.WriteLine( "cpx1 is false" ); + } + + Complex cpx2 = new Complex( 0, 0 ); + Console.WriteLine( "cpx2 is {0}", cpx2 ? "true" : "false" ); + } +} diff --git a/6_operators/6_complex_5.cs b/6_operators/6_complex_5.cs new file mode 100644 index 0000000..06221cb --- /dev/null +++ b/6_operators/6_complex_5.cs @@ -0,0 +1,47 @@ +using System; + +public struct Complex +{ + public Complex( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + // System.Object override + public override string ToString() { + return String.Format( "({0}, {1})", + real, + imaginary ); + } + + public double Magnitude { + get { + return Math.Sqrt( Math.Pow(this.real, 2) + + Math.Pow(this.imaginary, 2) ); + } + } + + public static implicit operator bool( Complex c ) { + return (c.real != 0) || (c.imaginary != 0); + } + + // Other methods ommitted for clarity. + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() { + Complex cpx1 = new Complex( 1.0, 3.0 ); + if( cpx1 ) { + Console.WriteLine( "cpx1 is true" ); + } else { + Console.WriteLine( "cpx1 is false" ); + } + + Complex cpx2 = new Complex( 0, 0 ); + Console.WriteLine( "cpx2 is {0}", cpx2 ? "true" : "false" ); + } +} diff --git a/6_operators/6_invalid_use_1.cs b/6_operators/6_invalid_use_1.cs new file mode 100644 index 0000000..7612e79 --- /dev/null +++ b/6_operators/6_invalid_use_1.cs @@ -0,0 +1,17 @@ +public class Apple +{ + public static Apple operator+( Apple rhs, Apple lhs ) { + // Method does nothing and exists only for example. + return rhs; + } +} + +public class GreenApple : Apple +{ + // INVALID!! -- Won't compile. + public static Apple operator+( Apple rhs, Apple lhs ) { + // Method does nothing and exists only for example. + return rhs; + } +} + diff --git a/7_exception_safety/7_employee_database_1.cs b/7_exception_safety/7_employee_database_1.cs new file mode 100644 index 0000000..d68797b --- /dev/null +++ b/7_exception_safety/7_employee_database_1.cs @@ -0,0 +1,7 @@ +using System.Collections; + +class EmployeeDatabase +{ + private ArrayList activeEmployees; + private ArrayList terminatedEmployees; +} diff --git a/7_exception_safety/7_employee_database_2.cs b/7_exception_safety/7_employee_database_2.cs new file mode 100644 index 0000000..1fec454 --- /dev/null +++ b/7_exception_safety/7_employee_database_2.cs @@ -0,0 +1,17 @@ +using System.Collections; + +class Employee +{ +} + +class EmployeeDatabase +{ + public void TerminateEmployee( int index ) { + object employee = activeEmployees[index]; + activeEmployees.RemoveAt( index ); + terminatedEmployees.Add( employee ); + } + + private ArrayList activeEmployees; + private ArrayList terminatedEmployees; +} diff --git a/7_exception_safety/7_employee_database_3.cs b/7_exception_safety/7_employee_database_3.cs new file mode 100644 index 0000000..3d0633b --- /dev/null +++ b/7_exception_safety/7_employee_database_3.cs @@ -0,0 +1,33 @@ +using System.Collections; + +class Employee +{ +} + +class EmployeeDatabase +{ + public void TerminateEmployee( int index ) { + object employee = null; + try { + employee = activeEmployees[index]; + } + catch { + // oops! We must be out of range here. + } + + if( employee != null ) { + activeEmployees.RemoveAt( index ); + + try { + terminatedEmployees.Add( employee ); + } + catch { + // oops! Allocation may have failed. + activeEmployees.Add( employee ); + } + } + } + + private ArrayList activeEmployees; + private ArrayList terminatedEmployees; +} diff --git a/7_exception_safety/7_employee_database_4.cs b/7_exception_safety/7_employee_database_4.cs new file mode 100644 index 0000000..6c74095 --- /dev/null +++ b/7_exception_safety/7_employee_database_4.cs @@ -0,0 +1,42 @@ +using System.Collections; + +class Employee +{ +} + +class EmployeeDatabase +{ + public void TerminateEmployee( int index ) { + // Clone sensitive objects. + ArrayList tempActiveEmployees = + (ArrayList) activeEmployees.Clone(); + ArrayList tempTerminatedEmployees = + (ArrayList) terminatedEmployees.Clone(); + + // Perform actions on temp objects. + object employee = tempActiveEmployees[index]; + tempActiveEmployees.RemoveAt( index ); + tempTerminatedEmployees.Add( employee ); + + // Now commit the changes. + ArrayList tempSpace = null; + ListSwap( ref activeEmployees, + ref tempActiveEmployees, + ref tempSpace ); + ListSwap( ref terminatedEmployees, + ref tempTerminatedEmployees, + ref tempSpace ); + } + + void ListSwap( ref ArrayList first, + ref ArrayList second, + ref ArrayList temp ) { + temp = first; + first = second; + second = temp; + temp = null; + } + + private ArrayList activeEmployees; + private ArrayList terminatedEmployees; +} diff --git a/7_exception_safety/7_employee_database_4a.cs b/7_exception_safety/7_employee_database_4a.cs new file mode 100644 index 0000000..5f04736 --- /dev/null +++ b/7_exception_safety/7_employee_database_4a.cs @@ -0,0 +1,49 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using System.Runtime.ConstrainedExecution; + +class Employee +{ +} + +class EmployeeDatabase +{ + public void TerminateEmployee( int index ) { + // Clone sensitive objects. + ArrayList tempActiveEmployees = + (ArrayList) activeEmployees.Clone(); + ArrayList tempTerminatedEmployees = + (ArrayList) terminatedEmployees.Clone(); + + // Perform actions on temp objects. + object employee = tempActiveEmployees[index]; + tempActiveEmployees.RemoveAt( index ); + tempTerminatedEmployees.Add( employee ); + + RuntimeHelpers.PrepareConstrainedRegions(); + try {} finally { + // Now commit the changes. + ArrayList tempSpace = null; + ListSwap( ref activeEmployees, + ref tempActiveEmployees, + ref tempSpace ); + ListSwap( ref terminatedEmployees, + ref tempTerminatedEmployees, + ref tempSpace ); + } + } + + [ReliabilityContract( Consistency.WillNotCorruptState, + Cer.Success )] + void ListSwap( ref ArrayList first, + ref ArrayList second, + ref ArrayList temp ) { + temp = first; + first = second; + second = temp; + temp = null; + } + + private ArrayList activeEmployees; + private ArrayList terminatedEmployees; +} diff --git a/7_exception_safety/7_employee_database_5.cs b/7_exception_safety/7_employee_database_5.cs new file mode 100644 index 0000000..aeb0918 --- /dev/null +++ b/7_exception_safety/7_employee_database_5.cs @@ -0,0 +1,41 @@ +using System; +using System.Runtime.Serialization; + +[Serializable()] +public class EmployeeVerificationException : Exception +{ + public enum Cause { + InvalidSSN, + InvalidBirthDate + } + + public EmployeeVerificationException( Cause reason ) + :base() { + this.reason = reason; + } + + public EmployeeVerificationException( Cause reason, + String msg ) + :base( msg ) { + this.reason = reason; + } + + public EmployeeVerificationException( Cause reason, + String msg, + Exception inner ) + :base( msg, inner ) { + this.reason = reason; + } + + protected EmployeeVerificationException( + SerializationInfo info, + StreamingContext context ) + :base( info, context ) { } + + private Cause reason; + public Cause Reason { + get { + return reason; + } + } +} diff --git a/7_exception_safety/7_exception_syntax_1.cs b/7_exception_safety/7_exception_syntax_1.cs new file mode 100644 index 0000000..c05cec4 --- /dev/null +++ b/7_exception_safety/7_exception_syntax_1.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; + +// Disable compiler warning: CS1058 +[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)] + +public class Entrypoint +{ + static void Main() { + try { + ArrayList list = new ArrayList(); + list.Add( 1 ); + + Console.WriteLine( "Item 10 = {0}", list[10] ); + } + catch( ArgumentOutOfRangeException x ) { + Console.WriteLine( "=== ArgumentOutOfRangeException"+ + " Handler ===" ); + Console.WriteLine( x ); + Console.WriteLine( "=== ArgumentOutOfRangeException"+ + " Handler ===\n\n" ); + } + catch( Exception x ) { + Console.WriteLine( "=== Exception Handler ===" ); + Console.WriteLine( x ); + Console.WriteLine( "=== Exception Handler ===\n\n" ); + } + catch { + Console.WriteLine( "=== Unexpected Exception" + + " Handler ===" ); + Console.WriteLine( "An exception I was not" + + " expecting..." ); + Console.WriteLine( "=== Unexpected Exception" + + " Handler ===" ); + } + finally { + Console.WriteLine( "Cleaning up..." ); + } + } +} diff --git a/7_exception_safety/7_exception_syntax_2.cs b/7_exception_safety/7_exception_syntax_2.cs new file mode 100644 index 0000000..3327cbc --- /dev/null +++ b/7_exception_safety/7_exception_syntax_2.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections; + +public class Entrypoint +{ + static void Main() { + try { + try { + ArrayList list = new ArrayList(); + list.Add( 1 ); + + Console.WriteLine( "Item 10 = {0}", list[10] ); + } + catch( ArgumentOutOfRangeException ) { + Console.WriteLine( "Do some useful work and" + + " then rethrow" ); + + // Rethrow caught exception. + throw; + } + finally { + Console.WriteLine( "Cleaning up..." ); + } + } + catch { + Console.WriteLine( "Done" ); + } + } +} diff --git a/7_exception_safety/7_exception_syntax_2a.cs b/7_exception_safety/7_exception_syntax_2a.cs new file mode 100644 index 0000000..f5fed7c --- /dev/null +++ b/7_exception_safety/7_exception_syntax_2a.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections; + +public class MyException : Exception +{ + public MyException( String reason, Exception inner ) + :base( reason, inner ) { + } +} + +public class Entrypoint +{ + static void Main() { + try { + try { + ArrayList list = new ArrayList(); + list.Add( 1 ); + + Console.WriteLine( "Item 10 = {0}", list[10] ); + } + catch( ArgumentOutOfRangeException x ) { + Console.WriteLine( "Do some useful work" + + " and then rethrow" ); + throw new MyException( "I'd rather throw this", + x ) ; + } + finally { + Console.WriteLine( "Cleaning up..." ); + } + } + catch( Exception x ) { + Console.WriteLine( x ); + Console.WriteLine( "Done" ); + } + } +} diff --git a/7_exception_safety/7_exception_syntax_3.cs b/7_exception_safety/7_exception_syntax_3.cs new file mode 100644 index 0000000..b5b2cf8 --- /dev/null +++ b/7_exception_safety/7_exception_syntax_3.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections; + +public class Entrypoint +{ + static void Main() { + try { + try { + ArrayList list = new ArrayList(); + list.Add( 1 ); + + Console.WriteLine( "Item 10 = {0}", list[10] ); + } + finally { + Console.WriteLine( "Cleaning up..." ); + throw new Exception( "I like to throw" ); + } + } + catch( ArgumentOutOfRangeException ) { + Console.WriteLine( "Oops! Argument out of range!" ); + } + catch { + Console.WriteLine( "Done" ); + } + } +} diff --git a/7_exception_safety/7_exception_syntax_4.cs b/7_exception_safety/7_exception_syntax_4.cs new file mode 100644 index 0000000..a750315 --- /dev/null +++ b/7_exception_safety/7_exception_syntax_4.cs @@ -0,0 +1,29 @@ +using System; + +public class Person +{ + ~Person() { + Console.WriteLine( "Cleaning up Person..." ); + Console.WriteLine( "Done Cleaning up Person..." ); + } +} + +public class Employee : Person +{ + ~Employee() { + Console.WriteLine( "Cleaning up Employee..." ); + object obj = null; + + // The following will throw an exception. + Console.WriteLine( obj.ToString() ); + Console.WriteLine( "Done cleaning up Employee..." ); + } +} + +public class Entrypoint +{ + static void Main() { + Employee emp = new Employee(); + emp = null; + } +} diff --git a/7_exception_safety/7_exception_syntax_5.cs b/7_exception_safety/7_exception_syntax_5.cs new file mode 100644 index 0000000..823c629 --- /dev/null +++ b/7_exception_safety/7_exception_syntax_5.cs @@ -0,0 +1,26 @@ +using System; +using System.IO; + +class EventLogger +{ + static EventLogger() { + eventLog = File.CreateText( "logfile.txt" ); + + // Statement below will throw an exception. + strLogName = (string) strLogName.Clone(); + } + + static public void WriteLog( string someText ) { + eventLog.Write( someText ); + } + + static private StreamWriter eventLog; + static private string strLogName; +} + +public class EntryPoint +{ + static void Main() { + EventLogger.WriteLog( "Log this!" ); + } +} diff --git a/7_exception_safety/7_rollback_1.cs b/7_exception_safety/7_rollback_1.cs new file mode 100644 index 0000000..e19b28d --- /dev/null +++ b/7_exception_safety/7_rollback_1.cs @@ -0,0 +1,82 @@ +using System; +using System.Diagnostics; + +public class Database +{ + public void Commit() { + Console.WriteLine( "Changes Committed" ); + } + + public void Rollback() { + Console.WriteLine( "Changes Abandoned" ); + } +} + +public class RollbackHelper : IDisposable +{ + public RollbackHelper( Database db ) { + this.db = db; + } + + ~RollbackHelper() { + Dispose( false ); + } + + public void Dispose() { + Dispose( true ); + } + + public void Commit() { + db.Commit(); + committed = true; + } + + private void Dispose( bool disposing ) { + // Don't do anything if already disposed. Remember, it is + // valid to call Dispose() multiple times on a disposable + // object. + if( !disposed ) { + // Remember, we don't want to do anything to the db if + // we got here from the finalizer because the database + // field could already be finalized! However, we do + // want to free any unmanaged resources. But, in this + // case, there are none. + if( disposing ) { + if( !committed ) { + db.Rollback(); + } + } else { + Debug.Assert( false, "Failed to call Dispose()" + + " on RollbackHelper" ); + } + } + } + + private Database db; + private bool disposed = false; + private bool committed = false; +} + +public class EntryPoint +{ + static private void DoSomeWork() { + using( RollbackHelper guard = new RollbackHelper(db) ) { + // Here we do some work that could throw an exception. + + // Comment out the following line to cause an + // exception. nullPtr.GetType(); + + // If we get here, we commit. + guard.Commit(); + } + + } + + static void Main() { + db = new Database(); + DoSomeWork(); + } + + static private Database db; + static private Object nullPtr = null; +} diff --git a/7_exception_safety/7_safe_handle_1.cs b/7_exception_safety/7_safe_handle_1.cs new file mode 100644 index 0000000..1bb9b37 --- /dev/null +++ b/7_exception_safety/7_safe_handle_1.cs @@ -0,0 +1,108 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.ConstrainedExecution; +using System.Security; +using System.Security.Permissions; +using System.Text; +using Microsoft.Win32.SafeHandles; + + +// +// Matches Win32 BLUETOOTH_FIND_RADIO_PARAMS +// +[StructLayout( LayoutKind.Sequential )] +class BluetoothFindRadioParams +{ + public BluetoothFindRadioParams() { + dwSize = 4; + } + public UInt32 dwSize; +} + +// +// Matches Win32 BLUETOOTH_RADIO_INFO +// +[StructLayout( LayoutKind.Sequential, + CharSet = CharSet.Unicode )] +struct BluetoothRadioInfo +{ + public const int BLUETOOTH_MAX_NAME_SIZE = 248; + + public UInt32 dwSize; + public UInt64 address; + [MarshalAs( UnmanagedType.ByValTStr, + SizeConst = BLUETOOTH_MAX_NAME_SIZE )] + public string szName; + public UInt32 ulClassOfDevice; + public UInt16 lmpSubversion; + public UInt16 manufacturer; +} + +// +// Safe Bluetooth Enumeration Handle +// +[SecurityPermission( SecurityAction.Demand, + UnmanagedCode = true )] +sealed public class SafeBluetoothRadioFindHandle + : SafeHandleZeroOrMinusOneIsInvalid +{ + private SafeBluetoothRadioFindHandle() : base( true ) { } + + override protected bool ReleaseHandle() { + return BluetoothFindRadioClose( handle ); + } + + [DllImport( "Irprops.cpl" )] + [ReliabilityContract( Consistency.WillNotCorruptState, + Cer.Success )] + [SuppressUnmanagedCodeSecurity] + private static extern bool BluetoothFindRadioClose( + IntPtr hFind ); +} + +public class EntryPoint +{ + private const int ERROR_SUCCESS = 0; + + static void Main() { + SafeFileHandle radioHandle; + using( SafeBluetoothRadioFindHandle radioFindHandle + = BluetoothFindFirstRadio(new BluetoothFindRadioParams(), + out radioHandle) ) { + if( !radioFindHandle.IsInvalid ) { + BluetoothRadioInfo radioInfo = new BluetoothRadioInfo(); + radioInfo.dwSize = 520; + UInt32 result = BluetoothGetRadioInfo( radioHandle, + ref radioInfo ); + + if( result == ERROR_SUCCESS ) { + // Let's send the contents of the radio info to the + // console. + Console.WriteLine( "address = {0:X}", + radioInfo.address ); + Console.WriteLine( "szName = {0}", + radioInfo.szName ); + Console.WriteLine( "ulClassOfDevice = {0}", + radioInfo.ulClassOfDevice ); + Console.WriteLine( "lmpSubversion = {0}", + radioInfo.lmpSubversion ); + Console.WriteLine( "manufacturer = {0}", + radioInfo.manufacturer ); + } + + radioHandle.Dispose(); + } + } + } + + [DllImport( "Irprops.cpl" )] + private static extern SafeBluetoothRadioFindHandle + BluetoothFindFirstRadio( [MarshalAs(UnmanagedType.LPStruct)] + BluetoothFindRadioParams pbtfrp, + out SafeFileHandle phRadio ); + + [DllImport( "Irprops.cpl" )] + private static extern UInt32 + BluetoothGetRadioInfo( SafeFileHandle hRadio, + ref BluetoothRadioInfo pRadioInfo ); +} diff --git a/7_exception_safety/7_using_1.cs b/7_exception_safety/7_using_1.cs new file mode 100644 index 0000000..9622da7 --- /dev/null +++ b/7_exception_safety/7_using_1.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; +using System.Text; + +public class EntryPoint +{ + public static void DoSomeStuff() { + // Open a file. + FileStream fs = File.Open( "log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None ); + Byte[] msg = new UTF8Encoding(true).GetBytes("Doing Some"+ + " Stuff"); + fs.Write( msg, 0, msg.Length ); + } + + public static void DoSomeMoreStuff() { + // Open a file. + FileStream fs = File.Open( "log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None ); + Byte[] msg = new UTF8Encoding(true).GetBytes("Doing Some"+ + " More Stuff"); + fs.Write( msg, 0, msg.Length ); + } + + static void Main() { + DoSomeStuff(); + + DoSomeMoreStuff(); + } +} diff --git a/7_exception_safety/7_using_2.cs b/7_exception_safety/7_using_2.cs new file mode 100644 index 0000000..e47cc03 --- /dev/null +++ b/7_exception_safety/7_using_2.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Text; + +public class EntryPoint +{ + public static void DoSomeStuff() { + // Open a file. + FileStream fs = null; + try { + fs = File.Open( "log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None ); + Byte[] msg = + new UTF8Encoding(true).GetBytes("Doing Some"+ + " Stuff\n"); + fs.Write( msg, 0, msg.Length ); + } + finally { + if( fs != null ) { + fs.Close(); + } + } + } + + public static void DoSomeMoreStuff() { + // Open a file. + FileStream fs = null; + try { + fs = File.Open( "log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None ); + Byte[] msg = + new UTF8Encoding(true).GetBytes("Doing Some"+ + " More Stuff\n"); + fs.Write( msg, 0, msg.Length ); + } + finally { + if( fs != null ) { + fs.Close(); + } + } + } + + static void Main() { + DoSomeStuff(); + + DoSomeMoreStuff(); + } +} diff --git a/7_exception_safety/7_using_3.cs b/7_exception_safety/7_using_3.cs new file mode 100644 index 0000000..336ffde --- /dev/null +++ b/7_exception_safety/7_using_3.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using System.Text; + +public class EntryPoint +{ + public static void DoSomeStuff() { + // Open a file. + using( FileStream fs = File.Open( "log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None ) ) { + Byte[] msg = + new UTF8Encoding(true).GetBytes("Doing Some" + + " Stuff\n"); + fs.Write( msg, 0, msg.Length ); + } + } + + public static void DoSomeMoreStuff() { + // Open a file. + using( FileStream fs = File.Open( "log.txt", + FileMode.Append, + FileAccess.Write, + FileShare.None ) ) { + Byte[] msg = + new UTF8Encoding(true).GetBytes("Doing Some" + + " More Stuff\n"); + fs.Write( msg, 0, msg.Length ); + } + } + + static void Main() { + DoSomeStuff(); + + DoSomeMoreStuff(); + } +} diff --git a/8_strings/8_carib_1.cs b/8_strings/8_carib_1.cs new file mode 100644 index 0000000..32e75a6 --- /dev/null +++ b/8_strings/8_carib_1.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; + +public class EntryPoint +{ + static void Main() { + CultureAndRegionInfoBuilder cib = null; + cib = new CultureAndRegionInfoBuilder( + "x-en-US-metric", + CultureAndRegionModifiers.None ); + + cib.LoadDataFromCultureInfo( new CultureInfo("en-US") ); + cib.LoadDataFromRegionInfo( new RegionInfo("US") ); + + // Make the change. + cib.IsMetric = true; + + // Create an LDML file. + cib.Save( "x-en-US-metric.ldml" ); + + // Register with the system. + cib.Register(); + } +} diff --git a/8_strings/8_carib_2.cs b/8_strings/8_carib_2.cs new file mode 100644 index 0000000..5609ded --- /dev/null +++ b/8_strings/8_carib_2.cs @@ -0,0 +1,10 @@ +using System; +using System.Globalization; + +public class EntryPoint +{ + static void Main() { + RegionInfo ri = new RegionInfo("x-en-US-metric"); + Console.WriteLine( ri.IsMetric ); + } +} diff --git a/8_strings/8_complex_1.cs b/8_strings/8_complex_1.cs new file mode 100644 index 0000000..4319e6f --- /dev/null +++ b/8_strings/8_complex_1.cs @@ -0,0 +1,54 @@ +using System; +using System.Text; +using System.Globalization; + +public struct Complex : IFormattable +{ + public Complex( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + // IFormattable implementation + public string ToString( string format, + IFormatProvider formatProvider ) { + StringBuilder sb = new StringBuilder(); + + if( format == "DBG" ) { + // Generate debugging output for this object. + sb.Append( this.GetType().ToString() + "\n" ); + sb.AppendFormat( "\treal:\t{0}\n", real ); + sb.AppendFormat( "\timaginary:\t{0}\n", imaginary ); + } else { + sb.Append( "( " ); + sb.Append( real.ToString(format, formatProvider) ); + sb.Append( " : " ); + sb.Append( imaginary.ToString(format, formatProvider) ); + sb.Append( " )" ); + } + + return sb.ToString(); + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() { + CultureInfo local = CultureInfo.CurrentCulture; + CultureInfo germany = new CultureInfo( "de-DE" ); + + Complex cpx = new Complex( 12.3456, 1234.56 ); + + string strCpx = cpx.ToString( "F", local ); + Console.WriteLine( strCpx ); + + strCpx = cpx.ToString( "F", germany ); + Console.WriteLine( strCpx ); + + Console.WriteLine( "\nDebugging output:\n{0:DBG}", + cpx ); + } +} diff --git a/8_strings/8_complex_2.cs b/8_strings/8_complex_2.cs new file mode 100644 index 0000000..52e189d --- /dev/null +++ b/8_strings/8_complex_2.cs @@ -0,0 +1,96 @@ +using System; +using System.Text; +using System.Globalization; + +public class ComplexDbgFormatter : ICustomFormatter, IFormatProvider +{ + // IFormatProvider implementation + public object GetFormat( Type formatType ) { + if( formatType == typeof(ICustomFormatter) ) { + return this; + } else { + return CultureInfo.CurrentCulture. + GetFormat( formatType ); + } + } + + // ICustomFormatter implementation + public string Format( string format, + object arg, + IFormatProvider formatProvider ) { + if( arg.GetType() == typeof(Complex) && + format == "DBG" ) { + Complex cpx = (Complex) arg; + + // Generate debugging output for this object. + StringBuilder sb = new StringBuilder(); + sb.Append( arg.GetType().ToString() + "\n" ); + sb.AppendFormat( "\treal:\t{0}\n", cpx.Real ); + sb.AppendFormat( "\timaginary:\t{0}\n", cpx.Img ); + return sb.ToString(); + } else { + IFormattable formatable = arg as IFormattable; + if( formatable != null ) { + return formatable.ToString( format, formatProvider ); + } else { + return arg.ToString(); + } + } + } +} + +public struct Complex : IFormattable +{ + public Complex( double real, double imaginary ) { + this.real = real; + this.imaginary = imaginary; + } + + public double Real { + get { return real; } + } + + public double Img { + get { return imaginary; } + } + + // IFormattable implementation + public string ToString( string format, + IFormatProvider formatProvider ) { + StringBuilder sb = new StringBuilder(); + sb.Append( "( " ); + sb.Append( real.ToString(format, formatProvider) ); + sb.Append( " : " ); + sb.Append( imaginary.ToString(format, formatProvider) ); + sb.Append( " )" ); + + return sb.ToString(); + } + + private double real; + private double imaginary; +} + +public class EntryPoint +{ + static void Main() { + CultureInfo local = CultureInfo.CurrentCulture; + CultureInfo germany = new CultureInfo( "de-DE" ); + + Complex cpx = new Complex( 12.3456, 1234.56 ); + + string strCpx = cpx.ToString( "F", local ); + Console.WriteLine( strCpx ); + + strCpx = cpx.ToString( "F", germany ); + Console.WriteLine( strCpx ); + + ComplexDbgFormatter dbgFormatter = + new ComplexDbgFormatter(); + strCpx = String.Format( dbgFormatter, + "{0:DBG}", + cpx ); + Console.WriteLine( "\nDebugging output:\n{0}", + strCpx ); + } +} diff --git a/8_strings/8_encoding_1.cs b/8_strings/8_encoding_1.cs new file mode 100644 index 0000000..d58302a Binary files /dev/null and b/8_strings/8_encoding_1.cs differ diff --git a/8_strings/8_formatting_1.cs b/8_strings/8_formatting_1.cs new file mode 100644 index 0000000..a3fb4b3 --- /dev/null +++ b/8_strings/8_formatting_1.cs @@ -0,0 +1,23 @@ +using System; +using System.Globalization; +using System.Windows.Forms; + +public class EntryPoint +{ + static void Main() { + CultureInfo current = CultureInfo.CurrentCulture; + CultureInfo germany = new CultureInfo( "de-DE" ); + CultureInfo russian = new CultureInfo( "ru-RU" ); + + double money = 123.45; + + string localMoney = money.ToString( "C", current ); + MessageBox.Show( localMoney, "Local Money" ); + + localMoney = money.ToString( "C", germany ); + MessageBox.Show( localMoney, "German Money" ); + + localMoney = money.ToString( "C", russian ); + MessageBox.Show( localMoney, "Russian Money" ); + } +} diff --git a/8_strings/8_formatting_2.cs b/8_strings/8_formatting_2.cs new file mode 100644 index 0000000..bb20143 --- /dev/null +++ b/8_strings/8_formatting_2.cs @@ -0,0 +1,21 @@ +using System; +using System.Globalization; +using System.Windows.Forms; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 3 ) { + Console.WriteLine( "Please provide 3 parameters" ); + return; + } + + string composite = + String.Format( "{0} + {1} = {2}", + args[0], + args[1], + args[2] ); + + Console.WriteLine( composite ); + } +} diff --git a/8_strings/8_regex_1.cs b/8_strings/8_regex_1.cs new file mode 100644 index 0000000..42fb1d8 --- /dev/null +++ b/8_strings/8_regex_1.cs @@ -0,0 +1,26 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + while( match.Success ) { + Console.WriteLine( "IP Address found at {0} with " + + "value of {1}", + match.Index, + match.Value ); + + match = match.NextMatch(); + } + + } +} diff --git a/8_strings/8_regex_2.cs b/8_strings/8_regex_2.cs new file mode 100644 index 0000000..875d773 --- /dev/null +++ b/8_strings/8_regex_2.cs @@ -0,0 +1,29 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + while( match.Success ) { + Console.WriteLine( "IP Address found at {0} with " + + "value of {1}", + match.Index, + match.Value ); + + match = match.NextMatch(); + } + + } +} diff --git a/8_strings/8_regex_3.cs b/8_strings/8_regex_3.cs new file mode 100644 index 0000000..e99f526 --- /dev/null +++ b/8_strings/8_regex_3.cs @@ -0,0 +1,35 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + while( match.Success ) { + Console.WriteLine( "IP Address found at {0} with " + + "value of {1}", + match.Index, + match.Value ); + Console.WriteLine( "Groups are:" ); + foreach( Group g in match.Groups ) { + Console.WriteLine( "\t{0} at {1}", + g.Value, + g.Index ); + } + + match = match.NextMatch(); + } + + } +} diff --git a/8_strings/8_regex_4.cs b/8_strings/8_regex_4.cs new file mode 100644 index 0000000..e9f48c7 --- /dev/null +++ b/8_strings/8_regex_4.cs @@ -0,0 +1,38 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + while( match.Success ) { + Console.WriteLine( "IP Address found at {0} with " + + "value of {1}", + match.Index, + match.Value ); + Console.WriteLine( "Groups are:" ); + Console.WriteLine( "\tPart 1: {0}", + match.Groups["part1"] ); + Console.WriteLine( "\tPart 2: {0}", + match.Groups["part2"] ); + Console.WriteLine( "\tPart 3: {0}", + match.Groups["part3"] ); + Console.WriteLine( "\tPart 4: {0}", + match.Groups["part4"] ); + + match = match.NextMatch(); + } + + } +} diff --git a/8_strings/8_regex_5.cs b/8_strings/8_regex_5.cs new file mode 100644 index 0000000..8c162ca --- /dev/null +++ b/8_strings/8_regex_5.cs @@ -0,0 +1,28 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"\k\." + + @"\k\." + + @"\k"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + while( match.Success ) { + Console.WriteLine( "IP Address found at {0} with " + + "value of {1}", + match.Index, + match.Value ); + + match = match.NextMatch(); + } + } +} diff --git a/8_strings/8_regex_6.cs b/8_strings/8_regex_6.cs new file mode 100644 index 0000000..820f7ef --- /dev/null +++ b/8_strings/8_regex_6.cs @@ -0,0 +1,22 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"([01]?\d\d?|2[0-4]\d|25[0-5])"; + Regex regex = new Regex( pattern ); + Console.WriteLine( "Input given --> {0}", + regex.Replace(args[0], + "xxx.xxx.xxx.xxx") ); + } +} diff --git a/8_strings/8_regex_7.cs b/8_strings/8_regex_7.cs new file mode 100644 index 0000000..dbaaa5f --- /dev/null +++ b/8_strings/8_regex_7.cs @@ -0,0 +1,35 @@ +using System; +using System.Text; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + + MatchEvaluator eval = new MatchEvaluator( + EntryPoint.IPReverse ); + Console.WriteLine( regex.Replace(args[0], + eval) ); + } + + static string IPReverse( Match match ) { + StringBuilder sb = new StringBuilder(); + sb.Append( match.Groups["part4"] + "." ); + sb.Append( match.Groups["part3"] + "." ); + sb.Append( match.Groups["part2"] + "." ); + sb.Append( match.Groups["part1"] ); + return sb.ToString(); + } +} diff --git a/8_strings/8_regex_7a.cs b/8_strings/8_regex_7a.cs new file mode 100644 index 0000000..5c31aa7 --- /dev/null +++ b/8_strings/8_regex_7a.cs @@ -0,0 +1,26 @@ +using System; +using System.Text; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])\." + + @"(?[01]?\d\d?|2[0-4]\d|25[0-5])"; + Regex regex = new Regex( pattern ); + Match match = regex.Match( args[0] ); + + string replace = @"${part4}.${part3}.${part2}.${part1}" + + @" (the reverse of $&)"; + Console.WriteLine( regex.Replace(args[0], + replace) ); + } +} diff --git a/8_strings/8_regex_8.cs b/8_strings/8_regex_8.cs new file mode 100644 index 0000000..d532cfa --- /dev/null +++ b/8_strings/8_regex_8.cs @@ -0,0 +1,48 @@ +using System; +using System.Text.RegularExpressions; + +public class EntryPoint +{ + static void Main( string[] args ) { + if( args.Length < 1 ) { + Console.WriteLine( "You must provide a string." ); + return; + } + + // Create regex to search for IP address pattern. + string pattern = @" +# First part match +([01]?\d\d? # At least one digit, + # possibly prepended by 0 or 1 + # and possibly followed by another digit +# OR + |2[0-4]\d # Starts with a 2, after a number from 0-4 + # and then any digit +# OR + |25[0-5]) # 25 followed by a number from 0-5 + +\. # The whole group is followed by a period. + +# REPEAT +([01]?\d\d?|2[0-4]\d|25[0-5])\. + +# REPEAT +([01]?\d\d?|2[0-4]\d|25[0-5])\. + +# REPEAT +([01]?\d\d?|2[0-4]\d|25[0-5]) +"; + Regex regex = new Regex( pattern, + RegexOptions.IgnorePatternWhitespace ); + Match match = regex.Match( args[0] ); + while( match.Success ) { + Console.WriteLine( "IP Address found at {0} with " + + "value of {1}", + match.Index, + match.Value ); + + match = match.NextMatch(); + } + + } +} diff --git a/8_strings/8_string_literals_1.cs b/8_strings/8_string_literals_1.cs new file mode 100644 index 0000000..daa81ad --- /dev/null +++ b/8_strings/8_string_literals_1.cs @@ -0,0 +1,28 @@ +using System; + +public class EntryPoint +{ + static void Main( string[] args ) { + string lit1 = "c:\\windows\\system32"; + string lit2 = @"c:\windows\system32"; + + string lit3 = @" +Jack and Jill +Went up the hill... +"; + Console.WriteLine( lit3 ); + + Console.WriteLine( "Object.RefEq(lit1, lit2): {0}", + Object.ReferenceEquals(lit1, lit2) ); + + if( args.Length > 0 ) { + Console.WriteLine( "Parameter given: {0}", + args[0] ); + + string strNew = String.Intern( args[0] ); + + Console.WriteLine( "Object.RefEq(lit1, strNew): {0}", + Object.ReferenceEquals(lit1, strNew) ); + } + } +} diff --git a/8_strings/8_stringbuilder_1.cs b/8_strings/8_stringbuilder_1.cs new file mode 100644 index 0000000..304c11c --- /dev/null +++ b/8_strings/8_stringbuilder_1.cs @@ -0,0 +1,21 @@ +using System; +using System.Text; + +public class EntryPoint +{ + static void Main() { + StringBuilder sb = new StringBuilder(); + + sb.Append("StringBuilder ").Append("is ") + .Append("very... "); + + string built1 = sb.ToString(); + + sb.Append("cool"); + + string built2 = sb.ToString(); + + Console.WriteLine( built1 ); + Console.WriteLine( built2 ); + } +} diff --git a/8_strings/x-en-US-metric.ldml b/8_strings/x-en-US-metric.ldml new file mode 100644 index 0000000..0469c1e --- /dev/null +++ b/8_strings/x-en-US-metric.ldml @@ -0,0 +1,369 @@ + + + + ldml version 1.1 + + + + + 244 + 1 + + + eng + en + + + + USA + US + USA + + + + + + + + + + + + + + + + 1033 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 279 + 216 + + + + + + + + + + January + February + March + April + May + June + July + August + September + October + November + December + + + + Jan + Feb + Mar + Apr + May + Jun + Jul + Aug + Sep + Oct + Nov + Dec + + + + January + February + March + April + May + June + July + August + September + October + November + December + + + + Jan + Feb + Mar + Apr + May + Jun + Jul + Aug + Sep + Oct + Nov + Dec + + + + + + + + Sunday + Monday + Tuesday + Wednesday + Thursday + Friday + Saturday + + + Sun + Mon + Tue + Wed + Thu + Fri + Sat + + + Su + Mo + Tu + We + Th + Fr + Sa + + + + + + + + + + AM + PM + + + + + + dddd, MMMM dd, yyyy + + + MMMM dd, yyyy + + + dddd, dd MMMM, yyyy + + + dd MMMM, yyyy + + + + + + M/d/yyyy + + + M/d/yy + + + MM/dd/yy + + + MM/dd/yyyy + + + yy/MM/dd + + + yyyy-MM-dd + + + dd-MMM-yy + + + + + + MMMM, yyyy + + + + MMMM dd + + + + + + + + + h:mm:ss tt + + + hh:mm:ss tt + + + H:mm:ss + + + HH:mm:ss + + + + + + h:mm tt + + + hh:mm tt + + + H:mm + + + HH:mm + + + + + + HH:mm:ss + + + + + + + + + + + , + . + , + % + Infinity + -Infinity + NaN + + + - + + . + , + + + + 2 + + + + + + + + 3 + 3 + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + + + + + $ + US Dollar + + USD + US Dollar + + + + + \ No newline at end of file diff --git a/9781590598733.jpg b/9781590598733.jpg new file mode 100644 index 0000000..d0e16bc Binary files /dev/null and b/9781590598733.jpg differ diff --git a/9_arrays_collections/9_array_1.cs b/9_arrays_collections/9_array_1.cs new file mode 100644 index 0000000..70c99f7 --- /dev/null +++ b/9_arrays_collections/9_array_1.cs @@ -0,0 +1,15 @@ +using System; + +public class EntryPoint +{ + static void Main() { + int[] array1 = new int[ 10 ]; + for( int i = 0; i < array1.Length; ++i ) { + array1[i] = i*2; + } + + int[] array2 = new int[] { 2, 4, 6, 8 }; + + int[] array3 = { 1, 3, 5, 7 }; + } +} diff --git a/9_arrays_collections/9_array_2.cs b/9_arrays_collections/9_array_2.cs new file mode 100644 index 0000000..29f4eae --- /dev/null +++ b/9_arrays_collections/9_array_2.cs @@ -0,0 +1,16 @@ +using System; + +public class Animal { } +public class Dog : Animal { } +public class Cat : Animal { } + +public class EntryPoint +{ + static void Main() { + Dog[] dogs = new Dog[ 3 ]; + Cat[] cats = new Cat[ 2 ]; + + Animal[] animals = dogs; + Animal[] moreAnimals = cats; + } +} diff --git a/9_arrays_collections/9_bidirectional_iterator_1.cs b/9_arrays_collections/9_bidirectional_iterator_1.cs new file mode 100644 index 0000000..fc7c427 --- /dev/null +++ b/9_arrays_collections/9_bidirectional_iterator_1.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + LinkedList intList = new LinkedList(); + for( int i = 1; i < 6; ++i ) { + intList.AddLast( i ); + } + + BidirectionalIterator iter = + new BidirectionalIterator(intList, + intList.First, + TIteratorDirection.Forward); + + foreach( int n in iter ) { + Console.WriteLine( n ); + + if( n == 5 ) { + iter.Direction = TIteratorDirection.Backward; + } + } + } +} + +public enum TIteratorDirection { + Forward, + Backward +}; + +public class BidirectionalIterator : IEnumerable +{ + public BidirectionalIterator( LinkedList list, + LinkedListNode start, + TIteratorDirection dir ) { + enumerator = CreateEnumerator( list, + start, + dir ).GetEnumerator(); + enumType = enumerator.GetType(); + } + + public TIteratorDirection Direction { + get { + return (TIteratorDirection) enumType.GetField("dir").GetValue( enumerator ); + } + set { + enumType.GetField("dir").SetValue( enumerator, + value ); + } + } + + private IEnumerator enumerator; + private Type enumType; + + private IEnumerable CreateEnumerator( LinkedList list, + LinkedListNode start, + TIteratorDirection dir ) { + LinkedListNode current = null; + do { + if( current == null ) { + current = start; + } else { + if( dir == TIteratorDirection.Forward ) { + current = current.Next; + } else { + current = current.Previous; + } + } + + if( current != null ) { + yield return current.Value; + } + } while( current != null ); + } + + public IEnumerator GetEnumerator() { + return enumerator; + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } +} + diff --git a/9_arrays_collections/9_circular_iterator_1.cs b/9_arrays_collections/9_circular_iterator_1.cs new file mode 100644 index 0000000..c01c47b --- /dev/null +++ b/9_arrays_collections/9_circular_iterator_1.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + LinkedList intList = new LinkedList(); + for( int i = 1; i < 6; ++i ) { + intList.AddLast( i ); + } + + CircularIterator iter = + new CircularIterator(intList, + intList.First); + + int counter = 0; + foreach( int n in iter ) { + Console.WriteLine( n ); + + if( counter++ == 100 ) { + iter.Stop(); + } + } + } +} + +public class CircularIterator : IEnumerable +{ + public CircularIterator( LinkedList list, + LinkedListNode start ) { + enumerator = CreateEnumerator( list, + start, + false ).GetEnumerator(); + enumType = enumerator.GetType(); + } + + public void Stop() { + enumType.GetField("stop").SetValue( enumerator, true ); + } + + private IEnumerator enumerator; + private Type enumType; + + private IEnumerable CreateEnumerator( LinkedList list, + LinkedListNode start, + bool stop ) { + LinkedListNode current = null; + do { + if( current == null ) { + current = start; + } else { + current = current.Next; + if( current == null ) { + current = start; + } + } + + yield return current.Value; + } while( !stop ); + } + + public IEnumerator GetEnumerator() { + return enumerator; + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } +} + diff --git a/9_arrays_collections/9_enumerable_1.cs b/9_arrays_collections/9_enumerable_1.cs new file mode 100644 index 0000000..a6dbf93 --- /dev/null +++ b/9_arrays_collections/9_enumerable_1.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; + +public class EntryPoint +{ + static public IEnumerable Powers( int from, + int to ) { + for( int i = from; i <= to; ++i ) { + yield return (int) Math.Pow( 2, i ); + } + } + + static void Main() { + IEnumerable powers = Powers( 0, 16 ); + foreach( int result in powers ) { + Console.WriteLine( result ); + } + } +} diff --git a/9_arrays_collections/9_jagged_1.cs b/9_arrays_collections/9_jagged_1.cs new file mode 100644 index 0000000..afb4904 --- /dev/null +++ b/9_arrays_collections/9_jagged_1.cs @@ -0,0 +1,30 @@ +using System; +using System.Text; + +public class EntryPoint +{ + static void Main() { + int[][] jagged = new int[3][]; + + jagged[0] = new int[] { 1, 2}; + jagged[1] = new int[] {1, 2, 3, 4, 5}; + jagged[2] = new int[] {6, 5, 4}; + + foreach( int[] ar in jagged ) { + StringBuilder sb = new StringBuilder(); + foreach( int n in ar ) { + sb.AppendFormat( "{0} ", n ); + } + Console.WriteLine( sb.ToString() ); + } + Console.WriteLine(); + + for( int i = 0; i < jagged.Length; ++i ) { + StringBuilder sb = new StringBuilder(); + for( int j = 0; j < jagged[i].Length; ++j ) { + sb.AppendFormat( "{0} ", jagged[i][j] ); + } + Console.WriteLine( sb.ToString() ); + } + } +} diff --git a/9_arrays_collections/9_multidim_1.cs b/9_arrays_collections/9_multidim_1.cs new file mode 100644 index 0000000..70e52a3 --- /dev/null +++ b/9_arrays_collections/9_multidim_1.cs @@ -0,0 +1,16 @@ +using System; + +public class EntryPoint +{ + static void Main() { + int[,] twoDim1 = new int[5,3]; + + int[,] twoDim2 = { {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} }; + + foreach( int i in twoDim2 ) { + Console.WriteLine( i ); + } + } +} diff --git a/9_arrays_collections/9_multidim_2.cs b/9_arrays_collections/9_multidim_2.cs new file mode 100644 index 0000000..fac3fec --- /dev/null +++ b/9_arrays_collections/9_multidim_2.cs @@ -0,0 +1,26 @@ +using System; + +public class EntryPoint +{ + static void Main() { + int[,] twoDim = { {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9} }; + + for( int i = 0; i != twoDim.GetLength(0); ++i ) { + for( int j = 0; j != twoDim.GetLength(1); ++j ) { + Console.WriteLine( twoDim[i,j] ); + } + } + + for( int i = twoDim.GetLowerBound(0); + i <= twoDim.GetUpperBound(0); + ++i ) { + for( int j = twoDim.GetLowerBound(1); + j <= twoDim.GetUpperBound(1); + ++j ) { + Console.WriteLine( twoDim[i,j] ); + } + } + } +} diff --git a/9_arrays_collections/9_my_collection_1.cs b/9_arrays_collections/9_my_collection_1.cs new file mode 100644 index 0000000..2796833 --- /dev/null +++ b/9_arrays_collections/9_my_collection_1.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +public class MyCollection : Collection +{ + public MyCollection() : base() { + } + + public MyCollection( IList list ) + : base(list) { } + + public MyCollection( IEnumerable enumerable ) + : base() { + foreach( T item in enumerable ) { + this.Add( item ); + } + } + + public MyCollection( IEnumerator enumerator ) + : base() { + while( enumerator.MoveNext() ) { + this.Add( enumerator.Current ); + } + } +} + +public class EntryPoint +{ + static void Main() { + MyCollection coll = + new MyCollection( GenerateNumbers() ); + + foreach( int n in coll ) { + Console.WriteLine( n ); + } + } + + static IEnumerable GenerateNumbers() { + for( int i = 4; i >= 0; --i ) { + yield return i; + } + } +} diff --git a/9_arrays_collections/9_mycoll_1.cs b/9_arrays_collections/9_mycoll_1.cs new file mode 100644 index 0000000..a060c5e --- /dev/null +++ b/9_arrays_collections/9_mycoll_1.cs @@ -0,0 +1,79 @@ +using System; +using System.Threading; +using System.Collections; +using System.Collections.Generic; + +public class MyColl : IEnumerable +{ + public MyColl( T[] items ) { + this.items = items; + } + + public IEnumerator GetEnumerator() { + return new NestedEnumerator( this ); + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + // The enumerator definition. + class NestedEnumerator : IEnumerator + { + public NestedEnumerator( MyColl coll ) { + Monitor.Enter( coll.items.SyncRoot ); + this.index = -1; + this.coll = coll; + } + + public T Current { + get { return current; } + } + + object IEnumerator.Current { + get { return Current; } + } + + public bool MoveNext() { + if( ++index >= coll.items.Length ) { + return false; + } else { + current = coll.items[index]; + return true; + } + } + + public void Reset() { + current = default(T); + index = 0; + } + + public void Dispose() { + try { + current = default(T); + index = coll.items.Length; + } + finally { + Monitor.Exit( coll.items.SyncRoot ); + } + } + + private MyColl coll; + private T current; + private int index; + } + + private T[] items; +} + +public class EntryPoint +{ + static void Main() { + MyColl integers = + new MyColl( new int[] {1, 2, 3, 4} ); + + foreach( int n in integers ) { + Console.WriteLine( n ); + } + } +} diff --git a/9_arrays_collections/9_mycoll_2.cs b/9_arrays_collections/9_mycoll_2.cs new file mode 100644 index 0000000..2263e97 --- /dev/null +++ b/9_arrays_collections/9_mycoll_2.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +public class MyColl : IEnumerable +{ + public MyColl( T[] items ) { + this.items = items; + } + + public IEnumerator GetEnumerator() { + foreach( T item in items ) { + yield return item; + } + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + private T[] items; +} + +public class EntryPoint +{ + static void Main() { + MyColl integers = + new MyColl( new int[] {1, 2, 3, 4} ); + + foreach( int n in integers ) { + Console.WriteLine( n ); + } + } +} diff --git a/9_arrays_collections/9_mycoll_3.cs b/9_arrays_collections/9_mycoll_3.cs new file mode 100644 index 0000000..1c6d796 --- /dev/null +++ b/9_arrays_collections/9_mycoll_3.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +public class MyColl : IEnumerable +{ + public MyColl( T[] items ) { + this.items = items; + } + + public IEnumerator GetEnumerator() { + lock( items.SyncRoot ) { + for( int i = 0; i < items.Length; ++i ) { + yield return items[i]; + } + } + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + private T[] items; +} + +public class EntryPoint +{ + static void Main() { + MyColl integers = + new MyColl( new int[] {1, 2, 3, 4} ); + + foreach( int n in integers ) { + Console.WriteLine( n ); + } + } +} diff --git a/9_arrays_collections/9_mycoll_4.cs b/9_arrays_collections/9_mycoll_4.cs new file mode 100644 index 0000000..3d90a40 --- /dev/null +++ b/9_arrays_collections/9_mycoll_4.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading; +using System.Collections; +using System.Collections.Generic; + +public class MyColl : IEnumerable +{ + public MyColl( T[] items ) { + this.items = items; + } + + public IEnumerator GetEnumerator( bool synchronized ) { + if( synchronized ) { + Monitor.Enter( items.SyncRoot ); + } + try { + int index = 0; + while( true ) { + if( index < items.Length ) { + yield return items[index++]; + } else { + yield break; + } + } + } + finally { + if( synchronized ) { + Monitor.Exit( items.SyncRoot ); + } + } + } + + public IEnumerator GetEnumerator() { + return GetEnumerator( false ); + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + private T[] items; +} + +public class EntryPoint +{ + static void Main() { + MyColl integers = + new MyColl( new int[] {1, 2, 3, 4} ); + + foreach( int n in integers ) { + Console.WriteLine( n ); + } + } +} diff --git a/9_arrays_collections/9_mycoll_5.cs b/9_arrays_collections/9_mycoll_5.cs new file mode 100644 index 0000000..89af43c --- /dev/null +++ b/9_arrays_collections/9_mycoll_5.cs @@ -0,0 +1,75 @@ +using System; +using System.Threading; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; + +public struct ImmutableBool +{ + public ImmutableBool( bool b ) { + this.b = b; + } + + public bool Value { + get { return b; } + } + + private bool b; +} + +public class MyColl : IEnumerable +{ + public MyColl( T[] items ) { + this.items = items; + } + + public IEnumerator GetEnumerator( + ImmutableBool synchronized ) { + if( synchronized.Value ) { + Monitor.Enter( items.SyncRoot ); + } + try { + foreach( T item in items ) { + yield return item; + } + } + finally { + if( synchronized.Value ) { + Monitor.Exit( items.SyncRoot ); + } + } + } + + public IEnumerator GetEnumerator() { + return GetEnumerator( new ImmutableBool(false) ); + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + + private T[] items; +} + +public class EntryPoint +{ + static void Main() { + MyColl integers = + new MyColl( new int[] {1, 2, 3, 4} ); + + IEnumerator enumerator = + integers.GetEnumerator( new ImmutableBool(true) ); + + // Get reference to synchronized field. + object field = enumerator.GetType(). + GetField("synchronized").GetValue( enumerator ); + + while( enumerator.MoveNext() ) { + Console.WriteLine( enumerator.Current ); + + // Throws an exception. + field.GetType().GetProperty("Value"). + SetValue( field, false, null ); + } + } +} diff --git a/9_arrays_collections/9_reverse_iterator_1.cs b/9_arrays_collections/9_reverse_iterator_1.cs new file mode 100644 index 0000000..e4363a6 --- /dev/null +++ b/9_arrays_collections/9_reverse_iterator_1.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; + +public class EntryPoint +{ + static void Main() { + List intList = new List(); + intList.Add( 1 ); + intList.Add( 2 ); + intList.Add( 3 ); + intList.Add( 4 ); + + foreach( int n in CreateReverseIterator(intList) ) { + Console.WriteLine( n ); + } + } + + static IEnumerable CreateReverseIterator( IList list ) { + int count = list.Count; + for( int i = count-1; i >= 0; --i ) { + yield return list[i]; + } + } +} diff --git a/9_arrays_collections/9_vector_1.cs b/9_arrays_collections/9_vector_1.cs new file mode 100644 index 0000000..79a610a --- /dev/null +++ b/9_arrays_collections/9_vector_1.cs @@ -0,0 +1,16 @@ +public class EntryPoint +{ + static void Main() { + int val = 123; + int newVal; + + int[] vector = new int[1]; + int[,] array = new int[1,1]; + + vector[0] = val; + array[0,0] = val; + + newVal = vector[0]; + newVal = array[0,0]; + } +} diff --git a/9_arrays_collections/coll_initializer_1.cs b/9_arrays_collections/coll_initializer_1.cs new file mode 100644 index 0000000..4ad2e23 --- /dev/null +++ b/9_arrays_collections/coll_initializer_1.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +public class Employee +{ + public string Name { get; set; } +} + +public class CollInitializerExample +{ + static void Main() { + var developmentTeam = new List { + new Employee { Name = "Michael Bolton" }, + new Employee { Name = "Samir Nagheenanajar" }, + new Employee { Name = "Peter Gibbons" } + }; + + Console.WriteLine( "Development Team:" ); + foreach( var employee in developmentTeam ) { + Console.WriteLine( "\t" + employee.Name ); + } + } +} diff --git a/9_arrays_collections/implicitly_typed_arrays_1.cs b/9_arrays_collections/implicitly_typed_arrays_1.cs new file mode 100644 index 0000000..c54d577 --- /dev/null +++ b/9_arrays_collections/implicitly_typed_arrays_1.cs @@ -0,0 +1,21 @@ +using System; + +public class EntryPoint +{ + static void Main() { + // A conventional array + int[] conventionalArray = new int[] { 1, 2, 3 }; + + // An implicitly typed array + var implicitlyTypedArray = new [] { 4, 5, 6 }; + Console.WriteLine( implicitlyTypedArray.GetType() ); + + // An array of doubles + var someNumbers = new [] { 3.1415, 1, 6 }; + Console.WriteLine( someNumbers.GetType() ); + + // Won't compile! + // var someStrings = new [] { "int", + // someNumbers.GetType() }; + } +} diff --git a/9_arrays_collections/implicitly_typed_arrays_2.cs b/9_arrays_collections/implicitly_typed_arrays_2.cs new file mode 100644 index 0000000..deb7674 --- /dev/null +++ b/9_arrays_collections/implicitly_typed_arrays_2.cs @@ -0,0 +1,38 @@ +using System; + +public struct A +{ + public A( int i ) { + this.i = i; + } + + public static implicit operator B( A a ) { + return new B( a.i ); + } + + private int i; +} + +public struct B +{ + public B( int j ) { + this.j = j; + } + + public static implicit operator A( B b ) { + return new A( b.j ); + } + + private int j; +} + +public class EntryPoint +{ + static void Main() { + A a = new A( 42 ); + B b = a; + + // Won't compile! + // var newArray = new [] { a, b }; + } +} diff --git a/9_arrays_collections/implicitly_typed_arrays_3.cs b/9_arrays_collections/implicitly_typed_arrays_3.cs new file mode 100644 index 0000000..db61a3d --- /dev/null +++ b/9_arrays_collections/implicitly_typed_arrays_3.cs @@ -0,0 +1,18 @@ +using System; + +public class EntryPoint { + static void Main() { + var threeByThree = new [] { + new [] { 1, 2, 3 }, + new [] { 4, 5, 6 }, + new [] { 7, 8, 9 } + }; + + foreach( var i in threeByThree ) { + foreach( var j in i ) { + Console.Write( "{0}, ", j ); + } + Console.Write( "\n" ); + } + } +} diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..5add460 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Freeware License, some rights reserved + +Copyright (c) 2007 Trey Nash + +Permission is hereby granted, free of charge, to anyone obtaining a copy +of this software and associated documentation files (the "Software"), +to work with the Software within the limits of freeware distribution and fair use. +This includes the rights to use, copy, and modify the Software for personal use. +Users are also allowed and encouraged to submit corrections and modifications +to the Software for the benefit of other users. + +It is not allowed to reuse, modify, or redistribute the Software for +commercial use in any way, or for a user’s educational materials such as books +or blog articles without prior permission from the copyright holder. + +The above copyright notice and this permission notice need to be included +in all copies or substantial portions of the software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..8484465 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +#Apress Source Code + +This repository accompanies [*Accelerated C# 2008*](http://www.apress.com/9781590598733) by Trey Nash (Apress, 2007). + +![Cover image](9781590598733.jpg) + +Download the files as a zip using the green button, or clone the repository to your machine using Git. + +##Releases + +Release v1.0 corresponds to the code in the published book, without corrections or updates. + +##Contributions + +See the file Contributing.md for more information on how you can contribute to this repository. diff --git a/README_FIRST.html b/README_FIRST.html new file mode 100644 index 0000000..d296719 --- /dev/null +++ b/README_FIRST.html @@ -0,0 +1,165 @@ + + + + + + + + +README + + + + + + + + +
+ +

This zip file includes virtually all of the source code in Accelerated C# 2008.  +Not every source file contains a static Main() method, therefore, those files will +not compile.  For the files that do compile, they can typically be built +by invoking the C# compiler (csc.exe) +from the command line as shown below:

+ +

 

+ +

csc +/debug+ <filename>

+ +

 

+ +

Where <filename> +is replaced with the C# file you want to compile.  Of course, /debug+ is optional, but I’m assuming +you may want to step through the code using cordbg or DbgCLR.

+ +

 

+ +

I have included a file named build.proj which is an msbuild +project file.  You can use it to build +all of the code snippets in one operation by executing the following command +from a Visual Studio 2008 command prompt:

+ +

 

+ +

msbuild +/t:Compile

+ +

 

+ +

If you examine the msbuild project file, you will +see that you can also build the code from each individual chapter if you like.

+ +

 

+ +

Have fun!

+ +
+ + + + diff --git a/build.proj b/build.proj new file mode 100644 index 0000000..b8e648a --- /dev/null +++ b/build.proj @@ -0,0 +1,240 @@ + + + + v3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..f6005ad --- /dev/null +++ b/contributing.md @@ -0,0 +1,14 @@ +# Contributing to Apress Source Code + +Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. + +## How to Contribute + +1. Make sure you have a GitHub account. +2. Fork the repository for the relevant book. +3. Create a new branch on which to make your change, e.g. +`git checkout -b my_code_contribution` +4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. +5. Submit a pull request. + +Thank you for your contribution! \ No newline at end of file diff --git a/intro_to_c_sharp/hello_world.cs b/intro_to_c_sharp/hello_world.cs new file mode 100644 index 0000000..e3e2171 --- /dev/null +++ b/intro_to_c_sharp/hello_world.cs @@ -0,0 +1,6 @@ +class EntryPoint +{ + static void Main() { + System.Console.WriteLine( "Hello World!" ); + } +} diff --git a/intro_to_c_sharp/hello_world_2.cs b/intro_to_c_sharp/hello_world_2.cs new file mode 100644 index 0000000..4da197d --- /dev/null +++ b/intro_to_c_sharp/hello_world_2.cs @@ -0,0 +1,8 @@ +using System; + +class EntryPoint +{ + static void Main() { + Console.WriteLine( "Hello World!" ); + } +}