CAD System Web Site - Computer Aided Design Software
i NET1000.COM
by Makoto Honda
Last Update: 2011-August-03                                    Update Info     Site Index     Licensing     Copyright Notice     Privacy Policy     Contact Us  
 

 

HOME

_________________

C# Note
_________________

                                               Return to   C# / WPF Implementation        

 Important C# Features       

 

   Mouse Wheel Event Handler             2011-Dec-29                        

  /////////////////////////////////////////////////////////////////77//////////
  public CView(CDoc pDoc, CData pData) // constructor
  {
    InitializeComponent(); // to show geometry defined in XAML

    this.MouseWheel += new MouseWheelEventHandler(CView_MouseWheel);

    InitialViewDefault();
  }
  /////////////////////////////////////////////////////////////////77////////// 
  void CView_MouseWheel(object sender, MouseWheelEventArgs e)
  {
    double factor = 0.6;
    double xxx = factor;
    double yyy = factor;

    if (e.Delta < 0) {xxx = yyy = -xxx; }
    Point p = new Point(xxx, yyy); 
    OnMMZoomMoveCamera(p);
  }

   Dictionary              2011-Dec-15                        

   Dictionary<string, int> dic = new Dictionary<string, int>();

   dic.Add ("cat", 2);

   dic.Add ("dog", 3);

   dic ["cat"] = 1;  // changing value

   dic ["tree"] = 3; // if a key does not exist, it will be added

   if (dic.ContainsKey ("dog") == true ) ...

   if (dic.ContainsValue (3) == false) ...

   int value = dic ["dog"];

   foreach (var p in dic)
   {
      Conslole.WriteLine ("{0}, {1}", p.Key, p.Value);
   }

   dic.Remove ("cat");

   dic.Remove ("myDog"); // do nothing

   dic.Clear();  // empty all

   int size = dic.Count;

 

   Lambda Expression              2011-July-31                        

   1)  =>   ... This is the Lambda operator. It is pronounced as "goes to".

   2)  The left side of the Lambda operator is INPUT and the right side is the EXPRESSION.

         delegate int Del (int i);
         Del myDelegate = x => x * x;
         int y = myDelegate (5);

   Lambdas can refer to "outer variables" that are in scope in the enclosing method
   or type in which the lambda is defined. Variables that are captured in this manner
   are stored for use in the lambda expression even after variables go out of scope.
   An outer variable must be assigned before it can be used in a lambda expression...

   //////////////////////////////////////////////////////////
   public delegate bool D1 ();
   public delegate bool D2 ( int i );

   public class LambdaTest
   {
        public D1 myDelegateA;
        public D2 myDelegateB;

        public void Testing(int val)
        {
             int j = 0;

           
 // Initialize a delegate with Lambda expression...
             myDelegateA = () => { j = 10; return j > val; };

           
 // Initialize another delegate with Lambda expression...
             myDelegateB = (x) => { return x == j; };

           
 // Check the value of "j" before calling delegates...
             Console.WriteLine("j = {0}", j);
  // j = 0

           
 // Invoke the first delegate...
             bool b = myDelegateA();
             Console.WriteLine("j = {0} b = {1}", j, b);  
// j = 10, b = true (val = 5)
        }
   }
   static void MainC()
   {
        LambdaTest test = new LambdaTest();
        test.Testing(5);

      
 // Invoke the second delegate with 9...
        bool b = test.myDelegateB(9);

        Console.WriteLine("b = {0}", b); 
 // j = 10, x = 9, so b = false

   }
 

   Two Kinds of Equality              2011-June-29                        

   1)  Reference equality ---   also known as "identity".
         Two references point to the same object.

   2)  Value equality ---   generally understood meaning of equality.
        Two objects contain the same values.

   If two objects have reference equality, they also have value equality, but the opposite is not always true.

   For reference types  (a la class objects), by default, the operator == and Equals() test for reference equality. Therefore, reference types
   typically need not override the default implementation of operator ==  and Equals(), if reference equality is what is needed.

   For value-type objects  (a la struct objects), and even for reference-type objects, if value equality is desired,
   you must override the default implementation of System.Object.Equals().
   You must also provide an overloaded operator == for struct (which does not come with overloaded operator== at all),
   and override the default overloaded operator == for class.

   //////////////////////////////////////////////////////////
   class Point2D : System.Object
   {
        public readonly int x, y;
        public Point2D (int x, int y)  //constructor
        {
             this.x = x;  this.y = y;
        }
        public override bool Equals (System.Object obj)
        {
             // If parameter is null return false.
             if (obj == null) return false;
        
             // If parameter cannot be cast to Point return false.
             Point2D p = obj as Point2D;
             if ((System.Object)p == null) return false;
             // Return true if the fields match:
             return (x == p.x) && (y == p.y);
        }
        public bool Equals (Point2D p)
        {
             // If parameter is null return false:
             if ((object)p == null) return false;
             // Return true if the fields match:
             return (x == p.x) && (y == p.y);
        }
        public override int GetHashCode ()   // Better to override GetHasCode also:
        {
             return x ^ y;
        }
   }
   //////////////////////////////////////////////////////////
   class Point3D : Point2D
   {
        public readonly int z;
        public Point3D (int x, int y, int z)
        : base (x, y)
        {
             this.z = z;
        }
        public override bool Equals (System.Object obj)
        {
             // If parameter cannot be cast to Point3D return false:
             Point3D p = obj as Point3D;
             if ((object) p == null) return false;
             return base.Equals (obj) && z == p.z; // Must call base class Equals...
        } 
        public bool Equals (Point3D p)
        {
             // Return true if the fields match:
             return base.Equals ((Point2D)p) && z == p.z;
        }
        public override int GetHashCode()
        {
             return base.GetHashCode() ^ z;
        }
        public static bool operator == (Point3D a, Point3D b)
        {
             // If both are null, or both are same instance, return true.
             if (System.Object.ReferenceEquals (a, b)) return true;
             // If one is null, but not both, return false.
             if (((object) a == null) || ((object) b == null)) return false;
             // Return true if the fields match:
             return a.x == b.x && a.y == b.y && a.z == b.z;
       }
       public static bool operator != (Point3D a, Point3D b)
       {
             return ! (a == b);
       }
      //////////////////////////////////////////////////////////

      Point3D a1 = new Point3D (1, 1, 1);
      Point3D a2 = new Point3D (1, 1, 1);
      bool b1 = a1.Equals (a2);  // ----------------- TRUE
      bool b2 = (a1 == a2);   // ----------------- TRUE
      bool b3 = (System.Object.ReferenceEquals (a1, a2) );  // ------------- FALSE

   System.Object.Equals()          2011-June-27                         (p.254)

   Equals() returns "true" only if two objects being compared reference the same object instance in memory.
   However, if you want Equals() to return true when the two variables being compared contain the same values,
   you must override Equals() as below:

   //////////////////////////////////////////////////////////
   public override bool Equals (object obj)  // Overriding Equals() method
   {
        return obj.ToString () == this.ToString ();
   }
   VALUE-EQUALITY vs. REFERENCE-EQUALITY
   FOR VALUE-TYPE & REFERENCE-TYPE...
   bool bFlag = x.Equals (y);

   Clearing Array Element Values          2011-June-27   

   Clearing Array Element Values
   An array has a fixed size.  Once created, the size cannot be changed. 
   Clear() will set the value of each element in the array to a default value (0 for int, false for bool, null for nullables ...)
   //////////////////////////////////////////////////////////
   int [] arr1 = { 1, 2, 3, 4, 5 };
   Array.Clear (arr);  // all set to 0
   Array.Clear (arr, start, number);  // Set to 0 the "number" of elements starting from index "start"

   C# Array Passing as Arguments          2011-June-27

   Once created, an array can be passed as an input / output argument of a method...

  
Passing an array to a method

   //////////////////////////////////////////////////////////
   static void SendArray (int [] myArr)  // Sending an array to a method
   {
        for (int i = 0; i < myArr.Length; i++)
        {  
             Console.WriteLine (" Index {0}   Value {1} ", i, myArr [i] );
        }
   }
   //////////////////////////////////////////////////////////
   static int [] ReturnArray ()
   {
        int [] arr = { 10, 20, 30, 40, 50 };
        return arr; 
   }
   //////////////////////////////////////////////////////////
   static void Main ()
   {
        int [] arr1 = { 1, 2, 3, 4, 5 };
        SendArray (arr1);

        int [] arr2 = ReturnArray ();
        for (int i = 0; i < arr2.Length; i++)
             Console.WriteLine (" Index {0}   Value {1} ", i, arr2 [i] );
   }

   C# Array Initialization Syntax          2011-June-27

   Declaring an array and filling the value of each element in the array are two different things. 
   There are a few different ways of initializing the element values.

  
Initialize by default values

   int size = 5;
   int [] iarr = new int [size];  // Initial values set to a default (0 for int, false for bool)

   Initialize by specific values

   int [] iarr = { 1, 2, 3, 4, 5 };   // Array size implicitly set
   int [] iarr = new int [] { 1, 2, 3, 4, 5 };  // "new" optional - see above
   int [] iarr = new int [5] { 1, 2, 3, 4, 5 };  // Array size must match the number of values, else compile error
   string [] sarr = new string [] { "aa", "bb", "cc" };  // string array
   bool [] barr = new bool [] { true, true, false, true };  // bool array
   bool [] barr = { true, false, true, false, true };  // bool array

   Class array

   int size = 5;
   CCFDPoint [] arr = new CCFDPoint [size];  // Array declared, but objects are not created yet...
   CCFDPoint [] arr = { new CCFDPoint (), new CCFDPoint (), new CCFDPoint () };  // All array elements created by the default constructor.

   Object array

   int size = 5;
   Object [] oarr = new Object [size];  // Everything comes from System.Object
   oarr [0] = 20;
   oarr [1] = "ABC";
   oarr [2] = false;
   oarr [3] = 3.1415;
    

   C# Class Array - Gotcha          2011-June-26

   In the code below, CCFDPoint is a "class" both in C++ & C#, and m_mxOrigin is a "class" in C++ but a "struct" in C#.
   C++ happily creates 5 CCFDPoint objects in the heap by new CCFDPoint [5], but C# does not; You have to create manually.
   Else,  NullReferenceException is thrown...

   int size = 5;
   _S_list = new CCFDPoint [size]; 

   for (int s = 0; s < size; s++)  S_list [s] = new CCFDPoint();  // This is needed for C# only

   _S_list [3].m_mxOrigin = pt.m_mxOrigin;  // NullReferenceException is thrown in C# if the above statement is missing...

   Structured Exception Handling      2011-June-14

  Throw an exception in a "try" block, and catch an exception in a "catch" block.
   Add a "finally" block to include the code that you want to execute after the catch block.

   System.Exception Properties:

   1. Message 
   2. Source
   3. TargetSite
   4. StackTrace --- you never set the value; it is established automatically at the exception time
   5. HelpLink  --- an empty string by default
   6. Data  --- the collection is empty, so check before displaying
   7. InnerException 
  

  Example 1.

  Try
  {
       throw new Exception (string.Format ("{0} has failed", name));
 // "Message" property --- 1
     
 - OR -   
       Exception ex = new Exception (string.Format ("{0} has failed", name));
 // "Message" property --- 1
       ex.HelpLink = "http://www.iNet1000.com";
 // "HelpLink" property ----------------- 5
       ex.Data.Add ("Time Stamp", string.Format ("{0}", DateTime.Now);
 // "Data" property --- 6
       ex.Data.Add ("Cause", "You bad");
 // "Data" property ------------------------------------------------------ 6
       throw ex;
  }

  catch (Exception e)
  {
       Console.WriteLine (" \n --- My Error ---");
       Console.WriteLine (" My Message: {0} ", e.Message); 
// "Message" property --- 1
       Console.WriteLine (" My Source: {0} ", e.Source); 
// "Source" property ---------- 2
       Console.WriteLine (" My Method: {0} ", e.TargetSite); 
// "TargetSite" property ------- 3
       Console.WriteLine (" My Stack: {0} ", e.StackTrace); 
// "StackTrace" property ------ 4
       Console.WriteLine (" My Help Link: {0} ", e.HelpLink); 
// "HelpLink" property  -------- 5
       if (e.Data != null)  
// "Data" property -- This collection is empty by default, so check first ---- 6
       {
            foreach (DictionaryEntry de in e.Data)
                 Console.WriteLine (" {0}: {1}: ", de.Key, de.Value);
       }
  }

  finally
  {
       // Always execute after catch()
  }

 
Console Output

  A first chance exception of type 'System.FormatException' occurred in mscorlib.dll

  --- My Error ---
  My Message: Input string was not in a correct format.
  My Source: mscorlib
  My Method: Double ParseDouble(System.String, System.Globalization.NumberStyles, System.Globalization.NumberFormatInfo)
  My Stack: at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
  at System.Double.Parse(String s)
  at ns_Main.MainWindow.txtKeyinPad_TextChanged(Object sender, TextChangedEventArgs e) in C:\1_CAD_G_SYSTEM...GProject_Main\MainWindow.xaml.cs:line 2570
  My Help Link:
 

   Delegate      2011-June-02

  Delegate is like a function pointer in C.  Delegate allows the signature definition of a method being passed.

  Example 1.

  In the following, three classes A, B and C are defined. They are not related (inheritance-wise), but there is dependency as C --> B --> A.
  That is, C is dependent on B, and B is dependent of A.  So, class C can access any of the B's methods, and class B can access any A's methods.
  But not in the opposite direction. The purpose of this exercise to allow class A to use C's method (MyMethod) - using a delegate.

 
NOTE:  Delegate is declared only once where it is used (here, in class A scope). No need to declare in class B scope again.
              Also note that in class C (where MyMethod is defined) there is no indication that it is used as a delegate.
              Below, class B can be completely removed, and class C can call class A directly.

  NOTE:  In the example below, if class C can pass its own pointer ("this") to class B (and class A), both class A and B can have access to C's methods.
              This eliminates the need to use a delegate altogether....
              But this necessitates that A and B have access to C's scope when declaring the pointer type of "this" being received.

  ------------------------------------------------------------------------------------------------------------------------------------------------------
  public class C
  {   
       public void MyMethod (int i) { ... }    
 // function to be passed as a delegate -----------
       . . .
       . . .
       B b = new B (MyMethod);  
// pass this function pointer as a delegate -----------
       . . .
   }

  ------------------------------------------------------------------------------------------------------------------------------------------------------
  public class B
  {   
       private
MyDelegate myDelegate; // declare delegate as a data member --------
(2) INSTANTIATE DELEGATE

       public B (
MyDelegate d)   // constructor ---------- (3) RECEIVE DELEGATE
   
   {
              this.myDelegate = d;  
// save delegate in member data ------- (4) SAVE DELEGATE
       }
       . . .
       . . .
       A a = new A (myDelegate);  
// pass this function as a delegate ----------- (5) PASS DELEGATE TO OTHERS
       . . .
   }

  ------------------------------------------------------------------------------------------------------------------------------------------------------
  public delegate void  MyDelegate (int i);   // delegate declaration (with signature) ------- (1) DECLARE DELEGATE
  public class A
  {   
       private
MyDelegate myDelegate;  // define a delegate as a data member --------
(2) INSTANTIATE DELEGATE

       public A (
MyDelegate d)   // Constructor takes a delegate as input ----------- (3) RECEIVE DELEGATE
   
   {                                     // (can be a separate method)
              this.myDelegate = d; 
 // Save delegate as member data ---------- (4) SAVE DELEGATE
       }
       . . .
       . . .
       myDelegate (5);   // Use delegate ------------------------ (5) INVOKE DELEGATE
       . . .
   }

  ------------------------------------------------------------------------------------------------------------------------------------------------------

  Example 2.

  class Plant
  {  
     delegate void myDelegate ();  // can have arguments ----------- (1) DEFINE DELEGATE

     private myDelegate d;   //---------------------------- (2) INSTANTIATE DELEGATE

     private A a;  // instantiate a;
     private B b;  // instantiate b;
     private C c;  // instantiate c;

     public Plant ();  // constructor
     {
           this.d += a.stopA;   // --- (3) ASSOCIATE DELEGATE with various methods by +=
           this.d += b.stopB;
           this.d += c.stopC;

           public void ShutDown ()
           {
                this.d ();   //  -------------- (4) INVOKE DELEGATE
           }
     }
  }
 

    Static        2011-May-19

     Static methods can be called directly without creating a class instance.

     Class A
     {
          static int Double (int a) { return a * 2; }
     }
 

    Stack vs. Heap        2011-May-19

     Stack: Value-based objects are allocated on the stack (destroyed quickly; lifetime defined by scope)

                  Examples: int, float, enum (System.ValueType)
                                       System-defined structures (ex. Point, Point3D, ...)
                                       User-defined structures (ex. my CPoint2D, CPoint3D, ...)

                  Usage:       Point p1;
                                       p1.X = 10;
                                       p1.Y = 20;

                                       or, using a new operator

                                      Point p1 = new Point();  // default constructor
                                      Point p2 = new Point(10, 20);  // overloaded constructor

                                      both are allocated on the stack.

     Heap: Reference-based objects are allocated on the managed heap (garbage-collected)

                  Examples: (System.Object)
                                       System-defined classes (ex.  ...)
                                       User-defined classes (ex. my CElemBase, ...)

                  Usage:      
CElemBase3D pE = new CElemBase3D();
                                      

    Passing Reference Types by Value        2011-May-23

     Both reference-types and value-types can be passed as parameters to methods.
     Further, reference-types can be passed
by value or by reference. (So can value-types.)

     Here is an example of passing a reference type (class Person) by value.

     class CPerson
     {
          public string Name;
          public int Age;
          public CPerson (string name, int age) { Name = name; Age = age; }
     }

     static void ModifyPerson (CPerson p)  // Pass by value (no parameter modifier such as out or ref)
     {
          p.Name = "Mary";
          p.Age = 30;
     }

     static void Main ()
     {
          CPerson Mike = new CPerson ("Mike", 20);
          ModifyPerson (Mike); 
          // --->  In the caller, 20-year-old Mike has now been converted to 30-year-old Mary....
     }

     Even passing by value (not out or ref), there is a side effect on the caller's variable!
     If we use struct SPerson, instead, this does not happen. See below...

     struct SPerson
     {
          public string Name;
          public int Age;
          public SPerson (string name, int age) { Name = name; Age = age; }
     }

     static void ModifyPerson (SPerson p)  // Pass by value (no parameter modifier such as out or ref)
     {
          p.Name = "Mary";
          p.Age = 30;
     }

     static void Main ()
     {
          SPerson Mike = new SPerson ("Mike", 20);
          ModifyPerson (Mike); 
          // --->  Here, Mike is not converted to Mary, thank goodness!
     }
 

    Class vs. Structure        2011-May-20

     In C++, struct is a legacy of the C language. There is no need to use struct in C++ (because a class can be created without any methods).
     In C#,
struct is resurrected with a different semantics. Syntactically, a struct is almost identical to class in C#. 
    The crucial difference is that struct is a
value-type while a class is a reference-type.

     class:  A reference-type and allocated in the .Net managed, garbage-collected, heap.
                 
 - The object in the heap is created only by using a new operator.  
               
   - When you assign one reference-type to another, you are equating the pointer, pointing to the same object in the heap.

     struct: A value-type and allocated in the stack. Its lifetime is predictable - deleted when out of scope.
                 
 - The object in the stack is created either by using or not using a new operator.  
                 
 - Cannot define a default constructor. One is automatically given.
               
   - Cannot use inheritance -  For that, you must use class.                
               
   - When you assign one value-type to another, a member-by-member copy of all field data is achieved.

     ------------------------------------------------------------------------------------------
     struct
SPoint
     {
          public int X;
          public int Y;

          public SPoint (int x, int y)  // non-default constructor
          {
               X = x; Y = y;
          }
          public void Increment ()
          {
               X++;  Y++;
          }
     }
     ----------------------------------------------------------------------------------------
     class CPoint
     {
          public int X;
          public int Y;

          public CPoint () // default constructor
          {
               X =  Y = 0;
          }
          public CPoint (int x, int y) // non-default constructor
          {
               X = x; Y = y;
          }
          public void Increment ()
          {
               X++;  Y++;
          }
     }
     ------------------------------------------------------------------------------------------
     SPoint p1;
     p1.X = 10;
     p1.Y = 20;  // all public data must be defined before use
     p1.Increment ();

     Or,

     SPoint p1 = new SPoint ();  // default constructor initializes all members to 0, false, or null
     SPoint p2 = p1;  // the assignment operator will make a copy of each member data

     If either p1 or p2 is changed, only that object is affected, not the other.
     This is a behavior we normally expect, so
struct is more "intuitive".
     If we use class CPerson, both will be affected... very "
counter-intuitive" BE CAREFUL!

     ------------------------------------------------------------------------------------------
     CPoint p1 = new CPoint (10, 20);
     p1.Increment ();

     CPoint p2 = p1;  // the assignment operator causes p1 and p2 point to the same object in the heap!!!


     If we want to do the same (make copy) using a class, do as follows:

     ------------------------------------------------------------------------------------------
     CPoint p1 = new CPoint (10, 20);
     CPoint p2 = new CPoint (p1);  // use a copy constructor, provided you have furnished one....

     public CPoint (CPoint p)  // copy constructor for C# class
     {
          X = p.X;  Y = p.Y;
     }
 

    Static class      2011-May-28

     public class MyMath
     {
          public static int noObjects = 0;
 //  use --> MyMath.noObjects  only one shared by all objects
          public static double Sqrt (double d); 
// use --> MyMath.Sqrt (2);  cannot access non-static member
          public const double PI = 3.1415;
 //  use --> MyMath.PI
     }

     static class

     - can contain only static members
     - The purpose of a static class is to act as a holder of utility
     - Can not instantiate (new)
     - Can have a static constructor if initialization is needed
         

    Static method      2011-June-17

     public class Math
     {
          public static double Sqrt (double d); 
// use --> Math.Sqrt (2)
          public const double PI = 3.1415;
 //  use --> Math.PI
     }

     static method

     - You can call a static method without instantiating an object of the class.
     - A static method cannot access any non-static fields/methods of the class.
     - To use a static method, just qualify with the class name --->  Math.Sqrt (4);
         
 

    Abstract class / method         2011-May-28

     An abstract class cannot be instantiated.  Only used as a base for other classes.    

     An abstract method forces a derived class to implement it.

     abstract class A
     {
          abstract void M ();
 //  a derived class must provide an implementation - In C++,  virtual void M() = 0;
     }

 

    Class Derivation / Inheritance        2011-May-28

     public abstract class C1
     {
          int X;
          public abstract void M1 ();
 //  abstract modifier forces a derived class to implement - In C++,  virtual void M() = 0;
          public  virtual void M2 () { X = 2; }   //  a derived class can override implementation
     }

     public abstract class C2 : C1  //  Itself being abstract, C2 need not fulfill contract of a derived class
     {
          public abstract void M3 ();
 //  a derived class must provide an implementation
          public virtual void M4 () {X = 4; }  //  a derived class can override implementation
     }

     public class C3 : C2
     {
          public override void M1 () { X = 10; } 
//  Must implement M1() since it was abstract
          public override void M2 () { X = 20; } 
//  Override M2()
          public override void M3 () { X = 30; }
 //  Must implement M3() since it was abstract
     }

 

    Array        2011-May-28

     C++  ---->  C#

     int arr [ 10 ];    ---->   int [ ] arr = new int [ 10 ];

     public CPoint2D pp [ 2 ] [ 3 ];    ---->   public CPoint2D [ , ]  pp = new CPoint2D [ 2, 3 ];

     In C#:

     void SetArrayint [ (out int [ ] arr )    //  Caller does not have to new the array, just declare it
    {
          arr = new int [ 10 ];
          arr [1] = 2;
          arr [2] = 3;
     }

    void SetArrayint [ (ref int [ ] arr )    //  Caller must define (new) the array
    {
          arr [1] = 2;
          arr [2] = 3;
     }

 

   Brute Force Conversion   from VC++/MFC/OpenGL code to C#/WPF         2011-March-12

During the port of my VC++ code (~50K lines) into C#, I did the following global replace. It took me a week to complete the task. That is, I was able to compile clean, and succeeded in creating a clean build! That, of course, does not mean all functions were working.

 1. Change file name from xxx.cpp to xxx.cs (add xxx.h into xxx.cs also).

 2. Delete all method declarations in xxx.h file - unless INLINE function (the body is there).
     Also, copy the argument list to the actual implementation (cpp) if there are "default arguments" defined.
     Also, the cpp file does not have a "virtual" modifier (only in .h), so careful when deleting declaration in .h.

 3. Put using "namespace" in xxx.cs file.

 4.
Put "public" in front of all data member, and all methods - just for now.

 5. Comment out "operator=" methods... not needed in C#.

 6. Comment out "Serialize methods" for now.

 7. Clone() methods should be --> public override CElemBase Clone() { return new CElemXXX(this); }   

 8. C# List - CElemBase is derived from object --->  public List<object> m_elemList = new List<object>();

 9. CPoint3D arr [ 10 ] --->  CPoint3D[ ] arr = new CPoint3D [ 10 ];
     CPoint3D arr2 [ 10 ] [ 20 ] --->  CPoint3D[, ] arr2 =
new CPoint3D [ 10, 20 ];

 10. All class member data (variables) of user-defined type must be created using "new".
 

 Replace All: GLfloat with double

 Replace All: float with double

 Replace All: public: with " " (none)

 Replace All: UINT with uint

 Replace All: CString with string

 Replace All: CGDoc:: with " " (none)

 Replace All: void with public void

 Replace All: const CPoint3D& with CPoint3D

 Replace All: ELEM_TYPE with  G.ELEM_TYPE

 Replace All: COOR_TYPE with  G.COORD_TYPE

 Replace All: COLORREF  with  G.G_COLOR

 Replace All: asin  with  Math.Asin   -- Math - sin/cos/tan...

 Replace All: "][" with  ", "       // A [2] [3] --> A [2, 3]

 Replace All: "};" with  "}"

 Replace All: "->" with  "."

 Replace All: BOOL with  bool

 Replace All: NULL with  null

 Replace All: ( const CPoint3D& A ) 
with  ( CPoint3D A )   --- input argument

 Replace All: ( CPoint3D* pA )  with  ( out CPoint3D pA )   --- output argument


 
In VC++:
 CObList m_elemList;
 m_elemList.AddTail(pE);
 m_elemList.RemoveAll();
 for (POSITION pos = m_elemList.GetHeadPosition (); pos != null; )
 {
        CElemBase pE = (CElemBox3D*) m_elemList.GetNext (pos);

 In C#:
 public List<object> m_elemList = new List<object>();
 m_elemList.Add(pE);
 m_elemList.Clear();
 foreach (CElemBase pE in m_elemList)
 {
 

   Conversion Note  of  GUtility.cpp          2011-March-12

  

  Description   C++   C#

  Abstract Class
 
You cannot instantiate from this class

  class A { virtual void method () = 0; }
 

   abstract class A { }
An abstract class need not fulfill all the contracts of the base class.

  Abstract Method -  forces a derived class to implement it

  class A { virtual void method () = 0; }

  abstract class A { abstract void method (); } 
  Virtual method - allows an override of the base implementation (an override can be further overridden...)   virtual void M () { --- }   public virtual void M () { --- } 
  ==> public override void M () { --- }

  Constructor - Visual Studio 2010 / Visual C# Express

  CPoint2D::CPoint2D (int x, int y)
  { X = x; Y = y; }
  public CPoint2D (int x, int y)
  { X = x; Y = y; }

  Copy Constructor - Visual Studio 2010 / Visual

  CPoint2D::CPoint2D (const CPoint2D& p)
  { X = p.x; Y = p.y; }
  public CPoint2D (CPoint2D p)
  { X = p.x; Y = p.y; }

  Destructor - Visual Studio 2010 / Visual C# Express

  ~CPoint2D::CPoint2D ()  { X = p.x; Y = p.y; }
  better not to have one ...  (delete operator does not exist in C#)

  Assignment Operator  - Visual Studio 2010 / Visual C# Express


   

 

 

  CPoint2D& CPoint2D::operator=
                   ( const CPoint2D& pt )
  {    if ( &pt == this ) return *this;
             // self-assignment check by address
             x = pt.x;
             y = pt.y;
             return *this; 
   }

  C# :    Not Needed in C#.

   

 

  Operator Overload - Visual Studio 2010 / Visual C# Express

  const CPoint2D CPoint2D::operator+
            (const CPoint2D& pt) const
  {
        return CPoint2D (x + pt.x, y + pt.y);
  }

  public static CPoint2D operator+
            (CPoint2D p1, CPoint2D p2)
  {
       return new CPoint2D (p1.x + p2.x, p1.y + p2.y);
  }

    Operator Overload 2 - Visual Studio 2010 / Visual C#

  CPoint2D CPoint2D::operator- ()
  {
       return CPoint2D (-x, -y);
  }
  public static CPoint2D operator -
            (CPoint2D p1)       // 2D Negation: N = -A;
  {
       return new CPoint2D (-p1.x, -p1.y);
  }

Declare user defined class - Visual Studio 2010 / Visual C# Express

  CPoint2D pt (1,2);   CPoint2D pt = new CPoint2D (1,2);

 Math  - Visual Studio 2010 / Visual C# Express

  abs (-) , arcsin (-), fabs, atan2, tan, ....  Math.Abs(-), Math.ArcSin(-), Math.ArcCos(-), Math.ArcTan2(-),,

 Array - Visual Studio 2010 /

  public:
        double arr [10];
        CPoint2D pt [10];   
  public double [ ] arr = new double [10];
 
public CPoint2D [] pt = new CPoint2D [10];

   Hash Table p.198 - Visual Studio 2010 / Visual C# Express

 C++ :  int ;
     C# :    int ;
 
  Constructor chaining  CElemBase1D::CElemBase1D
                         (int n, const CPoint3D& pt)
 : CElemBase (n, pt)
 { }
  public CElemBase1D (int n, CPoint3D pt)
  : base (n, pt)
  { }

 
  Base method call   CElemBase::Method (n);
 
base.Method (n);
 
 array initialization  int arr [ ] = { 1, 2, 3, 4 };  int [ ] arr = new int { 1, 2, 3, 4 };
pass an array argument   void M (int *  n);  void M ( int [ ] n );
copy / clone public virtual CElemBase* Clone () { return new CElemShapeL (*this); }
 
public virtual CElemBase Clone () { return new CElemShapeL (this); }
 
Retrieve elem from List for (Position pos = GetFirstElemPos(); pos != NULL)
{  n++;
   CElemBase* pE = GetNextElem(pos);
 
foreach (CElemBase p in m_pData.m_elemList)
{   p.XXX

 

     Array Argument          2011-May-19

From MS site - In this example, the array theArray is declared in the caller (MainA method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed.

class Test_Out
{
   
static void FillArr(out int[] arr)
    {
       
// Initialize the array:
        arr =
new int[5] { 1, 2, 3, 4, 5 };
    }
   
static void MainA()
    {
       
int[] arr2; // Initialization is not required

       
// Pass the array to the callee using out:
        FillArr(
out arr2);

       
// Display the array elements:
        System.
Console.WriteLine("Array elements are:");
       
for (int i = 0; i < arr2.Length; i++)
        {
            System.
Console.Write(arr2[i] + " ");
        }
    }
}

From MS site - In this example, the array arr is initialized in the caller (MainB method), and passed to ModifyArr method by using the ref parameter. Some of the array elements are updated in the ModifyArr method. Then, the array elements are returned to the caller and displayed.

class Test_Ref
{
    static void ModifyArr(ref int[] arr)
    {
        // Create the array on demand:
        if (arr == null)
        {
            arr = new int[5]; // Must initialize
        }
        // Modify the array:
        arr[2] = 20;
        arr[4] = 30;
    }
    static void MainB()
    {
        // Initialize the array:
        int[] arr = { 1, 2, 3, 4, 5 };

        // Pass the array using ref:
        ModifyArr(ref arr);

        // Display the updated array:
        System.Console.WriteLine("Array elements are:");
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write(arr[i] + " ");
        }
    }
}

    C# Language Tutorial       2011-March-5

C# Language Tutorial

Lambda Expression :   += () => { xxxx; }; 

     this.d += () => { a.stopA; };           // same as above, using Lambda expression
     this.d += () => { d.stopD (2); };      // can have a different argument list than DELEGATE 
     this.d += () => { d.stopE (3, 4); };  // can have a different argument list than DELEGATE


Event

class Plant
{   
     public delegate void myDelegate ();  // can have arguments ----------- (1) DEFINE DELEGATE
     public event myDelegate evt;  // ----- (2) INSTANTIATE EVENT (of type delegate)
}

Plant m = new Plant ();

m.evt += a.stopA;                      // ------- (3) SUBSCRIBE TO EVENT
m.evt += () => { d.stopD (4); }
m.evt += () => { e.stopE (3, 5); }

m.evt -= a.stopA;                       // ------- (4) UNSUBSCRIBE TO EVENT

m.evt ();     // ------------ (5) RAISE EVENT and invoke handler

 

Class

class Circle
{
     public Circle ()  // -- default constructor - does not take any parameters
     {
          radius = 0;
     }
     public Circle (int rad)   // -- overloaded constructor
     {
          radius = rad;   // -- or this.radius = rad;  if ambiguous
     }
     public double Area ()
     {
          return Math.PI * radius * radious;
     }
     private int radius;

     static void Doubler (ref int val)  // -- ref is like C++ & (reference)
     {
          val += val;
     }
}

Circle c = new Circle ();
double area = c.Area ();

 

Interfaces

   ==

 

Generics

1) Without using generics

using System.Collections;
...
Queue myQ = new Queue();
Circle c = new Circle();
myQ.Enqueue (c);
...
c = (Circle) myQ.Dequeue();   // --- must cast

2) Using generics

using System.Collections.Generic;   // --- use generic namespace
...
Queue<Circle> myQ = new Queue<Circle>();
Circle c = new Circle();
myQ.Enqueue (c);
...
c = myQ.Dequeue();   // --- no need to cast


C# Switch

   In a switch statement, break statement is mandatory for every case (even for the default case).


C# Keywords (not in C++)

   as  base  bool  byte  checked  decimal  delegate  event  explicit  extern  finally  fixed  foreach mplicit  internal 

   is  lock  namespace  object  out  override  params  readonly  ref  sbyte  sealed  stackalloc  ulong  unchecked

   unsafe  ushort  using  volatile


C# Identifiers (not reserved, but good to avoid using them)

  from  get  group  into  join  let  orderly  partial  select  set  value  where  yield
 

 

    C++ STL library Tutorial       2011-July-31

    STL Tutorial

   #include "stdafx.h"
   #include <iostream>
   #include <vector>
   #include <list>
   #include <string>
   #include <map>

   using namespace std;

   int main(int argc, _TCHAR* argv[])
   {
        //---------------------------------
string
        string a ("Hello world");
        cout << a << endl;

        a = "New string";
        string b = "ABC";
        string c = a + b;

        string d;

        bool bEmpty = d.empty();
        int capacity = c.capacity();
        int size = c.size();
        int length = c.length();
        c = c + a + b;

        c.append(" ZZZZ");
        c.replace(0, 2, "012345",6);
        d = c[0];

        c.assign( "_ASSIGN_", 5, 8); // start index, length
        int n = c.find("abc", 1);
        n = c.find_first_not_of( " ");
        n = c.find_first_of( "abc", 0);
        n = c.find_last_of( "abc");
        a = "01234567890";
        d = a.substr(2, 3);      // returns substring from start index, length
        n = a.compare(0, 3, "123");

        //----------------------- vector / insert at the end only

        vector<int> v;
        v.push_back(10);
        v.push_back(20);
        v.push_back(30);

        cout << v[0] << endl;

        for (int i = 0; i < v.size(); i++)
        {
             cout << v[i] << endl;
        }

        //-------------------------- list (int) / insert anywhere

        list<int> lst;
        lst.push_back(2);
        // insert at the end
        lst.push_front(5);
        // insert at the beginning
        lst.insert(++lst.begin(),8);
        // insert "8" before the first
        lst.insert(++lst.begin(),18);
        // insert "8" before the first
        lst.push_front(11);
        // insert "8" before the first
        for (int i = 0; i < lst.size(); i++)
        {
             // cout << *lst << endl;
        }

        list<int>::iterator i;
        for (i = lst.begin(); i != lst.end(); i++)
        {
             cout << *i << endl;
        }

        //----------------------------- list (class CPoint)

        list<CPoint> pts;

        CPoint* pp1 = new CPoint(1,2,3);
        CPoint* pp2 = new CPoint(1,2,3);
        CPoint* pp3 = new CPoint(1,2,3);
        pts.push_back(*pp1);    // insert at the end
        pts.push_back(*pp2);    // insert at the end
        pts.push_back(*pp3);    // insert at the end
        pts.push_front(*pp1);   // insert at the beginning
        CPoint p11 (11,12,13);

        pts.push_front(p11);   // insert at the beginning
        for (int i = 0; i < pts.size(); i++)
        {
             // cout << *lst << endl;
        }

        list<CPoint>::iterator ii;
        for (ii = pts.begin(); ii != pts.end(); ii++)
        {
             cout << (*ii).x << endl;
             cout << (*ii).y << endl;
             cout << (*ii).z << endl;
        }

        //---------------------------------------------------- map (int, string)
        // ... using integer as an array index
        map<int, string> hosts;
        hosts[1001] = "Piers Morgan";
        hosts[2002] = "Johny Carson";
        hosts[3015] = "David Letterman";
        cout << "hosts[1015] =" << hosts[1015] << endl;
        int hostSize = hosts.size();
        for ( map<int, string>::iterator i = hosts.begin(); i != hosts.end(); i++)
        {
             cout << (*i).first << " " << (*i).second << endl;
        }

        //---------------------------------------------------- map (string, int)
        // ... using "string" as an array index
        map<string, int> guests;
        guests["Angelina Jolie"] = 201;
        guests["Julian Moore"] = 311;
        guests["Diane Lane"] = 400;
        guests["Julia Roberts"] = 400;
        guests["Meryl Streep"] = 500;
        cout << "guests[Julia Roberts] =" << guests["Julia Roberts"] << endl;
        int guestSize = guests.size();
        for ( map<string, int>::iterator i = guests.begin(); i != guests.end(); i++)
        {
             cout << (*i).first << " " << (*i).second << endl;
        }

        return 0;
   }

        //----------------------------------- map iterator

       
// Car.h
        typedef std::map<int, AAA*> myMapList;
        myMapList m_carList;

        // Car.cpp
        // Free memory
        myMapList::iterator it = m_carList.begin();
        for ( ; it != m_carList.end(); it++ )
        {
             delete it -> second;  // or (*it).second;
        }
        m_carList.clear();


 

    "Julian Moore"] = 311;
    

 

 

CAD System Web Site - Computer Aided Design Software:  Copyright 2010-2013 Makoto Honda. All Rights Reserved.  

 

   

Copyright 2010-2013 Makoto Honda. All Rights Reserved.                                       www.iNET1000.com