PowerPoint Slides Currency symbols by MikeJenny

VIEWS: 18 PAGES: 99

PowerPoint Slides Currency symbols

More Info
									                                                                                                                    1




Programming in C#.NET




         ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      2




                 Lecture 3 – C# Basics II

Outline
1.   Operators
2.   Casts
3.   Delegates
4.   Events




                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      3

                      Overview

• The operators available in C#
• The idea of equality when dealing with reference and
  value types
• Data conversion between the primitive data types
• Converting value types to reference types using boxing
• Converting between reference types by casting
• Overloading the standard operators to support
  operations on the custom types you define
• Adding cast operators to the custom types you define to
  support seamless data type conversions



                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                     4

                                     Operators
Category                                    Operator
Arithmetic                                  +-*/%
Logical                                     &|^~&&||!
String concatenation                        +
Increment and decrement                     ++ --
Bit shifting                                << >>
Comparison                                  == != <> <= >=
Assignment                                  =+=-=*=/=%=&=|=^=<<=>>=
Member access (for objects and structs)     .
Indexing (for arrays and indexers)          []
Cast                                        ()
Conditional (the Ternary Operator)          ?:
Delegate concatenation and removal          +-
Object Creation                             new
Type information                            sizeof (unsafe code only) is typeof as
Overflow exception control                  checked unchecked
Indirection and Address                     *->& (unsafe code only) []
Namespace alias qualifier                   ::
Null coalescing operator                    ??


                                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      5

                       Operators

• One of the biggest pitfalls to watch out for when using
    C# operators is that, like other C-style languages, C#
    uses different operators for assignment =, and
    comparison ==. For instance, the following statement
    means let x equal three:
x = 3;
• If you now want to compare x to a value, you need to
    use the double equals sign ==:
if (x == 3)
• Fortunately, C#'s strict type safety rules prevent the
    very common C error where assignment is performed
    instead of comparison in logical statements. This means
    that in C# the following statement will generate a
    compiler error:
if (x = 3)

                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     6

                     Operators

• Visual Basic programmers who are accustomed to
  using the ampersand (&) character to concatenate
  strings will have to make an adjustment.
• In C#, the plus sign (+) is used instead, whereas &
  denotes a bit-wise AND between two different integer
  values.
• | allows you to perform a bit-wise OR between two
  integers.
• Visual Basic programmers also might not recognize the
  modulus (%) arithmetic operator.
• This returns the remainder after division, so for
  example x%5 returns 2 if x is equal to 7.

                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                             7

                     Operator Shortcuts

Shortcut Operator Equivalent To
x++, ++x         x=x+1
x--, --x         x=x–1
x+=y             x=x+y
x-=y             x=x-y
x*=y             x=x*y
x/=y             x=x/y
x%=y             x=x%y
x>>= y           x=x>>y
x<<= y           x=x<<y
x&=y             x=x&y
x|=y             x=x|y
x^=y             x=x^y


                                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  8

               Operator Shortcuts

int x = 5;
if (++x == 6)
{
    Console.WriteLine("This will execute");
}
if (x++ == 7)
{
    Console.WriteLine("This won't");
}

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  9

               Operator Shortcuts

int x = 5;
if (++x == 6)
{
    Console.WriteLine("This will execute");
}
if (x++ == 7)
{
    Console.WriteLine("This won't");
}

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      10

                Operator Shortcuts

• The first if condition evaluates to true, because x is
   incremented from 5 to 6 before the expression is
   evaluated. The condition in the second if statement is
   false, however, because x is incremented to 7 only after
   the entire expression has been evaluated (while x=6).
• The prefix and postfix operators --x and x-- behave in
   the same way, but decrement rather than increment the
   operand.
• The other shortcut operators, such as += and -=,
   require two operands, and are used to modify the value
   of the first operand by performing an arithmetic,
   logical, or bit-wise operation on it. For example, the
   next two lines are equivalent:
x += 5;
x = x + 5;

                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   11

             The Ternary Operator

• condition ? true_value : false_value




                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 12

            The Ternary Operator

int x = 1;
string s = x.ToString() + " ";
s += (x == 1 ? "man" : "men");
Console.WriteLine(s);




                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 13

  The checked and unchecked Operators

byte b = 255;
b++;
Console.WriteLine(b.ToString());

byte b = 255;
checked {
  b++;
}
Console.WriteLine(b.ToString());

                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      14

                     Type Safety

• Type Conversions
  – Implicit conversions
  – Explicit conversions
• Boxing and Unboxing




                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 15

              Type Conversions

byte value1 = 10;
byte value2 = 23;
byte total;
total = value1 + value2;
Console.WriteLine(total);




                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   16

              Implicit conversions

byte value1 = 10;
byte value2 = 23;
long total;         // this will compile fine
total = value1 + value2;
Console.WriteLine(total);




                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                          17

  implicit type conversions supported in C#.


From          To
sbyte         short, int, long, float, double, decimal
byte          short, ushort, int, uint, long, ulong, float, double,
              decimal
short         int, long, float, double, decimal
ushort        int, uint, long, ulong, float, double, decimal
int           long, float, double, decimal
uint          long, ulong, float, double, decimal
long, ulong   float, double, decimal
float         double
char          ushort, int, uint, long, ulong, float, double, decimal




                               ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                       18

                Implicit conversions

• Nullable types implicitly convert to other nullable types
  following the conversion rules described for non-
  nullable types in the previous table; that is, int?
  implicitly converts to long?, float?, double?, and
  decimal?.
• Non-nullable types implicitly convert to nullable types
  according to the conversion rules described in the
  preceding table; that is, int implicitly converts to long?,
  float?, double?, and decimal?.
• Nullable types do not implicitly convert to non-nullable
  types; you must perform an explicit conversion as
  described in the next section. This is because there is
  the chance a nullable type will have the value null,
  which cannot be represented by a non-nullable type.

                            ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   19

             Explicit conversions

• int to short — May lose data
• int to uint — May lose data
• uint to int — May lose data
• float to int — Will lose everything after the
  decimal point
• Any numeric type to char — Will lose data
• Decimal to any numeric type — Because the
  decimal type is internally structured differently
  from both integers and floating-point numbers
• int? to int — The nullable type may have the
  value null

                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      20

               Explicit conversions

long val = 30000;
int i = (int)val; // A valid cast.

long val = 3000000000;
int i = (int)val; // An invalid cast.

long val = 3000000000;
int i = checked ((int)val);



                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  21

             Explicit conversions

double price = 25.30;
int approximatePrice = (int)(price + 0.5);

ushort c = 43;
char symbol = (char)c;
Console.WriteLine(symbol);




                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  22

             Explicit conversions

struct ItemDetails {
public string Description;
public int ApproxPrice;
}
//...
double[] Prices = { 25.30, 26.20, 27.40, 30.00 };
ItemDetails id;
id.Description = "Whatever";
id.ApproxPrice = (int)(Prices[0] + 0.5);

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      23

              Explicit conversions

int? a = null;
int b = (int)a; // Will throw exception

int i = 10;
string s = i.ToString();

string s = "100";
int i = int.Parse(s);
Console.WriteLine(i + 50); // Add 50 to prove it
   is really an int
                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                         24

                Boxing and Unboxing

string s = 10.ToString();

int i = 20;
object o = i;

int i = 20;
object o = i; // Box the int
int j = (int)o; // Unbox it back into an int

long a = 333333423;
object b = (object)a;
int c = (int)b;

                              ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                      25

        Comparing Objects For Equality

• Comparing Reference Types for Equality
  –   The ReferenceEquals() method
  –   The virtual Equals() method
  –   The static Equals() method
  –   Comparison operator (==)
• Comparing Value Types for Equality




                           ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  26

       The ReferenceEquals() method

SomeClass x, y;
x = new SomeClass();
y = new SomeClass();
bool B1 = ReferenceEquals(null, null); // returns
  true
bool B2 = ReferenceEquals(null,x); // returns
  false
bool B3 = ReferenceEquals(x, y); // returns
  false because x and y point to different
  objects

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   27

    Comparing Reference Types for Equality

•   The ReferenceEquals() method
•   The virtual Equals() method
•   The static Equals() method
•   Comparison operator (==)

bool b = (x == y); // x, y object references




                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  28

    Comparing Value Types for Equality


bool b = ReferenceEquals(v,v); // v is a variable
  of some value type




                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  29

            Operator Overloading


Matrix a, b, c; // assume a, b and c have been
 initialized
Matrix d = c * (a + b);

Matrix d = c.Multiply(a.Add(b));




                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               30

             How Operators Work


int a = 3;
uint b = 2;
double d = 4.0;
long l = a + b;
double x = d + a;




                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               31

             How Operators Work


int a = 3;
uint b = 2;
double d = 4.0;
long l = a + b;
double x = d + a;




                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               32

             How Operators Work


int a = 3;
uint b = 2;
double d = 4.0;
long l = a + b;
double x = d + a;




                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   33

             How Operators Work


Vector vect1, vect2, vect3; // initialize vect1 and
  vect2
vect3 = vect1 + vect2;
vect1 = vect1*2;




                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                       34
 Operator Overloading Example: The Vector
                  Struct
namespace Wrox.ProCSharp.OOCSharp
{
   struct Vector
   {
          public double x, y, z;
          public Vector(double x, double y, double z)
          {
                    this.x = x;
                    this.y = y;
                    this.z = z;
          }
          public Vector(Vector rhs)
          {
                    x = rhs.x;
                    y = rhs.y;
                    z = rhs.z;
          }
          public override string ToString()
          {
                    return "( " + x + " , " + y + " , " + z + " )";
          }

                                            ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     35
    Operator Overloading Example: The Vector
                     Struct
        public static Vector operator + (Vector lhs,
     Vector rhs)
        {
              Vector result = new Vector(lhs);
              result.x += rhs.x;
              result.y += rhs.y;
              result.z += rhs.z;
              return result;
        }
     }
}
                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     36
    Operator Overloading Example: The Vector
                     Struct
        public static Vector operator + (Vector lhs,
     Vector rhs)
        {
              Vector result = new Vector(lhs);
              result.x += rhs.x;
              result.y += rhs.y;
              result.z += rhs.z;
              return result;
        }
     }
}
                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     37
 Operator Overloading Example: The Vector
                  Struct
static void Main()
{
   Vector vect1, vect2, vect3;
   vect1 = new Vector(3.0, 3.0, 1.0);
   vect2 = new Vector(2.0, -4.0, -4.0);
   vect3 = vect1 + vect2;
   Console.WriteLine("vect1 = " + vect1.ToString());
   Console.WriteLine("vect2 = " + vect2.ToString());
   Console.WriteLine("vect3 = " + vect3.ToString());
}


                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             38
Operator Overloading Example: The Vector
                 Struct

Vectors
vect1 = ( 3 , 3 , 1 )
 vect2 = ( 2 , -4 , -4 )
 vect3 = ( 5 , -1 , -3 )

                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                             39

                 Adding more overloads
public static Vector operator * (double lhs, Vector rhs)
{
   return new Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
}
public static Vector operator * (Vector lhs, double rhs)
 {
   return new Vector(rhs * lhs.x, rhs * lhs.y, rhs *lhs.z);
}
public static Vector operator * (Vector lhs, double rhs)
{
   return rhs * lhs;
}
public static double operator * (Vector lhs, Vector rhs)
 {
   return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;
}

                                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                            40

                              Adding more overloads
static void Main()
{
   // stuff to demonstrate arithmetic operations
   Vector vect1, vect2, vect3;
   vect1 = new Vector(1.0, 1.5, 2.0);
   vect2 = new Vector(0.0, 0.0, -10.0);
   vect3 = vect1 + vect2;
   Console.WriteLine("vect1 = " + vect1);
   Console.WriteLine("vect2 = " + vect2);
   Console.WriteLine("vect3 = vect1 + vect2 = " + vect3);
   Console.WriteLine("2*vect3 = " + 2*vect3);
   vect3 += vect2;
   Console.WriteLine("vect3+=vect2 gives " + vect3);
   vect3 = vect1*2;
   Console.WriteLine("Setting vect3=vect1*2 gives " + vect3);
   double dot = vect1*vect3;
   Console.WriteLine("vect1*vect3 = " + dot);
}                                ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            41

        Adding more overloads

Vectors2
vect1 = ( 1 , 1.5 , 2 )
vect2 = ( 0 , 0 , -10 )
vect3 = vect1 + vect2 = ( 1 , 1.5 ,
 -8 )
2*vect3 = ( 2 , 3 , -16 )
vect3+=vect2 gives ( 1 , 1.5 , -18 )
Setting vect3=vect1*2 gives ( 2 ,
 3,4)
                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             42

  Overloading the comparison operators

• == and !=
• > and <
• >= and <=




                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                       43

    Overloading the comparison operators

public static bool operator == (Vector lhs, Vector rhs)
{
  if (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z)
        return true;
  else
        return false;
}

public static bool operator != (Vector lhs, Vector rhs)
{
  return ! (lhs == rhs);
}

                            ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                          44

    Overloading the comparison operators

static void Main()
{
   Vector vect1, vect2, vect3;
   vect1 = new Vector(3.0, 3.0, -10.0);
   vect2 = new Vector(3.0, 3.0, -10.0);
   vect3 = new Vector(2.0, 3.0, 6.0);
   Console.WriteLine("vect1==vect2 returns " + (vect1==vect2));
   Console.WriteLine("vect1==vect3 returns " + (vect1==vect3));
   Console.WriteLine("vect2==vect3 returns " + (vect2==vect3));
   Console.WriteLine();
   Console.WriteLine("vect1!=vect2 returns " + (vect1!=vect2));
   Console.WriteLine("vect1!=vect3 returns " + (vect1!=vect3));
   Console.WriteLine("vect2!=vect3 returns " + (vect2!=vect3));
}


                               ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            45

 Overloading the comparison operators

Vectors3
vect1==vect2 returns True
vect1==vect3 returns False
vect2==vect3 returns False

vect1!=vect2 returns False
vect1!=vect3 returns True
vect2!=vect3 returns True
                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                              46

Which Operators Can You Overload?
   Category        Operators       Restrictions
   Arithmetic      +, *, /, -, %   None.
   binary
   Arithmetic      +, -, ++, --    None.
   unary
   Bitwise binary &, |, ^, <<, >> None.
   Bitwise unary   !, ~ true, false The true and false operators must be
                                    overloaded as a pair.
   Comparison      ==, != >=, <= >, Comparison operators must be overloaded
                   <,               in pairs.
   Assignment      +=, -=, *=, /=, You cannot explicitly overload these
                   >>=, <<=, %=,   operators; they are overridden
                   &=, |=, ^=      implicitly when you override the indi-
                                   vidual operators such as +, -, %, and so
                                   on.
   Index           []              You cannot overload the index operator
                                   directly. The indexer member type,
                                   discussed in Chapter 2, "C# Basics,"
                                   allows you to support the index operator
                                   on your classes and structs.
   Cast            ()              You cannot overload the cast operator
                                   directly. User-defined casts (discussed
                                   next) allow you to define custom cast
                                   behavior.


                                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                     47

               User-Defined Casts

int I = 3;
long l = I // implicit
short s = (short)I // explicit




                          ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   48

              User-Defined Casts

• When converting from an int to a short,
  because the short might not be large enough to
  hold the value of the int.
• When converting from signed to unsigned data
  types will return incorrect results if the signed
  variable holds a negative value.
• When converting from floating-point to integer
  data types, the fractional part of the number
  will be lost.
• When converting from a nullable type to a non-
  nullable type, a value of null will cause an
  exception.
                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                           49

        Implementing User-Defined Casts

struct Currency
{
   public uint Dollars;
   public ushort Cents;
   public Currency(uint dollars, ushort cents)
   {
        this.Dollars = dollars;
        this.Cents = cents;
   }
   public override string ToString()
   {
        return string.Format("${0}.{1,-2:00}", Dollars,Cents);
   }



                                ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  50

      Implementing User-Defined Casts

  Currency balance = new Currency(10,50);
  float f = balance; // We want f to be set to
  10.5

public static implicit operator float (Currency
  value)
{
  return value.Dollars + (value.Cents/100.0f);
}


                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               51

     Implementing User-Defined Casts

float amount = 45.63f;
Currency amount2 = (Currency)amount;

float amount = 45.63f;
Currency amount2 = amount; // wrong




                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                                52

              Implementing User-Defined Casts
static void Main()
{
      try
      {
              Currency balance = new Currency(50,35);
              Console.WriteLine(balance);
              Console.WriteLine("balance is " + balance);
              Console.WriteLine("balance is (using ToString()) " + balance.ToString());
              float balance2= balance;
              Console.WriteLine("After converting to float, = " + balance2);
              balance = (Currency) balance2;
              Console.WriteLine("After converting back to Currency, = " + balance);
              Console.WriteLine("Now attempt to convert out of range value of " + "-$100.00 to a Currency:");
              checked
              {
                            balance = (Currency) (-50.5);
                            Console.WriteLine("Result is " + balance.ToString());
              }
      }
      catch(Exception e)
       {
              Console.WriteLine("Exception occurred: " + e.Message);
      }
}




                                                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              53

     Implementing User-Defined Casts

SimpleCurrency
50.35
Balance is $50.35
Balance is (using ToString()) $50.35
After converting to float, = 50.35
After converting back to Currency, =
  $50.34
Now attempt to convert out of range value
  of -$100.00 to a Currency:
Result is $4294967246.60486
                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  54

      Implementing User-Defined Casts

public static explicit operator Currency (float
   value)
{
   checked
   {
       uint dollars = (uint)value;
       ushort cents = Convert.ToUInt16((value-
   dollars)*100);
       return new Currency(dollars, cents);
   }
 }
                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   55

            Casts between classes

• You cannot define a cast if one of the classes is
  derived from the other (these types of cast
  already exist, as you will see).
• The cast must be defined inside the definition
  of either the source or destination data type.




                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                    56

Casts between classes




         ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               57

          Casts between classes

public static explicit operator D(C value)
{
  // and so on
}
public static explicit operator C(D value)
{
  // and so on
}

                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               58

  Casts between base and derived classes

MyDerived derivedObject = new MyDerived();
MyBase baseCopy = derivedObject;

MyBase derivedObject = new MyDerived();
MyBase baseObject = new MyBase();
MyDerived derivedCopy1 = (MyDerived)
 derivedObject; // OK
MyDerived derivedCopy2 = (MyDerived)
 baseObject; // Throws exception


                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                59

  Casts between base and derived classes

class DerivedClass : BaseClass
{
  public DerivedClass(BaseClass rhs)
  {
       // initialize object from the Base
  instance
  } // etc.



                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                60

        Boxing and unboxing casts

Currency balance = new Currency(40,0);
object baseCopy = balance;

object derivedObject = new Currency(40,0);
object baseObject = new object();
Currency derivedCopy1 =
  (Currency)derivedObject; // OK
Currency derivedCopy2 =
  (Currency)baseObject; // Exception thrown


                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                61

              Multiple Casting

Currency balance = new Currency(10,50);
long amount = (long)balance;
double amountD = balance;

Currency balance = new Currency(10,50);
long amount = (long)(float)balance;
double amountD = (double)(float)balance;

Currency balance = new Currency(10,50);
long amount = balance;
                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               62

              Multiple Casting

public static implicit operator Currency
   (uint value)
{
   return new Currency(value/100u,
   (ushort)(value%100));
} // Don't do this!

uint bal = 350;
Currency balance = bal;
uint bal2 = (uint)balance;
                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               63

              Multiple Casting

public static implicit operator Currency
  (uint value)
{
  return new Currency(value, 0);
}

Currency balance = new Currency(50, 35);
ulong bal = (ulong) balance;

                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                               64

              Multiple Casting

public static implicit operator Currency
  (uint value)
{
  return new Currency(value, 0);
}
public static implicit operator uint
  (Currency value)
{
  return value.Dollars;
}
                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 65

               Multiple Casting

try
{
Currency balance = new Currency(50,35);
Console.WriteLine(balance);
Console.WriteLine("balance is " + balance);
Console.WriteLine("balance is (using ToString())
   " + balance.ToString());


uint balance3 = (uint) balance;
Console.WriteLine("Converting to uint gives " +
  balance3);
                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              66

             Multiple Casting

SimpleCurrency2
50 balance is $50.35 balance is (using
  ToString()) $50.35
Converting to uint gives 50
After converting to float, = 50.35
After converting back to Currency, =
  $50.34
Now attempt to convert out of range value
  of -$100.00 to a Currency:
Exception occurred: Arithmetic operation
  resulted in an overflow.
                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                         67

        Multiple Casting

Console.WriteLine(balan
 ce);
Console.WriteLine("bala
 nce is " + balance);
Console.WriteLine("bala
 nce is (using ToString())
 " + balance.ToString());
              ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  68

                   Summary

• This chapter looked at the standard operators
  provided by C#, described the mechanics of
  object equality, and examined how the
  compiler converts the standard data types from
  one to another. It also demonstrated how you
  can implement custom operator support on
  your data types using operator overloads.
  Finally, the chapter looked at a special type of
  operator overload, the cast operator, which
  allows you to specify how instances of your
  types are converted to other data types.

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 69

          Delegates and Events

• Delegates
• Anonymous Methods
• Events




                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 70

                  Delegates

• Starting Threads
• Generic Library Classes
• Events

void EntryPoint()
{
  // do whatever the new thread
  needs to do
}


                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             71

       Declaring Delegates in C#

delegate void VoidOperation(uint x);

delegate double TwoLongsOp(long
  first, long second);

delegate string GetAString();

public delegate string GetAString();



                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              72

          Using Delegates in C#

private delegate string GetAString();
static void Main(string[] args)
{
  int x = 40;
  GetAString firstStringMethod = new
  GetAString(x.ToString);
  Console.WriteLine("String is" +
  firstStringMethod());
  // With firstStringMethod initialized
  to x.ToString(),
  // the above statement is equivalent to
  saying
  // Console.WriteLine("String is" +
  x.ToString());

                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                                        73

                               Using Delegates in C#
struct Currency
{
      public uint Dollars;
      public ushort Cents;

     public Currency(uint dollars, ushort cents)
     {
              this.Dollars = dollars;
              this.Cents = cents;
     }

     public override string ToString()
     {
              return string.Format("${0}.{1,-2:00}", Dollars,Cents);
     }

     public static explicit operator Currency (float value)
     {
              checked
              {
                              uint dollars = (uint)value;
                              ushort cents = (ushort)((value-dollars)*100);
                              return new Currency(dollars, cents);
              }
     }

     public static implicit operator float (Currency value)
     {
              return value.Dollars + (value.Cents/100.0f);
     }

     public static implicit operator Currency (uint value)
     {
              return new Currency(value, 0);
     }

     public static implicit operator uint (Currency value)
     {
              return value.Dollars;
     }
}



                                                             ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  74

            Using Delegates in C#
private delegate string GetAString();
static void Main(string[] args)
{
  int x = 40;
  GetAString firstStringMethod = new
  GetAString(x.ToString);
  Console.WriteLine("String is " +
  firstStringMethod());
  Currency balance = new Currency(34, 50);
  firstStringMethod = new
  GetAString(balance.ToString);
  Console.WriteLine("String is " +
  firstStringMethod());
  firstStringMethod = new
  GetAString(Currency.GetCurrencyUnit);
  Console.WriteLine("String is " +
  firstStringMethod());

                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                        75

                Anonymous Methods
namespace ConsoleApplication1
{
   class Program
   {
        delegate string delegateTest(string val);
        static void Main(string[] args)
        {
               string mid = ", middle part,";
               delegateTest anonDel = delegate(string param)
               {
                       param += mid;
                       param += " and this was added to the
   string.";
                       return param;
               };
               Console.WriteLine(anonDel("Start of string"));
        }
   }
}



                             ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            76

         Anonymous Methods

{
  param += mid;
  param += " and this was added to
  the string.";
  return param;
};




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              77

         SimpleDelegate Example

class MathsOperations
{
  public static double
  MultiplyByTwo(double value)
  {
     return value*2;
  }
  public static double Square(double
  value)
  {
     return value*value;
  }
}
                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                          78

                      SimpleDelegate Example
using System;

namespace SimpleDelegate
{
     delegate double DoubleOp(double x);

    class MainEntryPoint
    {
           static void Main()
           {
                        DoubleOp [] operations =
                        {
                                    new DoubleOp(MathsOperations.MultiplyByTwo),
                                    new DoubleOp(MathsOperations.Square)
                        };

                        for (int i=0 ; i<operations.Length ; i++)
                        {
                                    Console.WriteLine("Using operations[{0}]:", i);
                                    ProcessAndDisplayNumber(operations[i], 2.0);
                                    ProcessAndDisplayNumber(operations[i], 7.94);
                                    ProcessAndDisplayNumber(operations[i], 1.414);
                                    Console.WriteLine();
                        }
            }

            static void ProcessAndDisplayNumber(DoubleOp action, double value)
            {
                        double result = action(value);
                        Console.WriteLine("Value is {0}, result of operation is {1}", value,
    result);
}




                                               ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                   79

           SimpleDelegate Example

ProcessAndDisplayNumber(operations[
  i], 2.0);

• operations[i] means the delegate (that is, the
  method represented by the delegate).
• operations[i](2.0) means actually call this
  method, passing in the value in parentheses.




                        ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              80

         SimpleDelegate Example

SimpleDelegate
Using operations[0]:
Value is 2, result of operation is 4
Value is 7.94, result of operation is
  15.88
Value is 1.414, result of operation is
  2.828

Using operations[1]:
Value is 2, result of operation is 4
Value is 7.94, result of operation is
  63.0436
Value is 1.414, result of operation is
  1.999396

                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                             81

                SimpleDelegate Example
static void Main()
{
   DoubleOp multByTwo = delegate(double val)
   {
         return val * 2;
   }
   DoubleOp square = delegate(double val)
   {
         return val * val;
   }

    DoubleOp [] operations = {multByTwo, square};

    for (int i=0 ; i<operations.Length ; i++)
    {
         Console.WriteLine("Using operations[{0}]:", i);
         ProcessAndDisplayNumber(operations[i], 2.0);
         ProcessAndDisplayNumber(operations[i], 7.94);
         ProcessAndDisplayNumber(operations[i], 1.414);
         Console.WriteLine();
    }
}



                                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                               82

                           BubbleSorter Example
for (int i = 0; i < sortArray.Length; i++)
{
     for (int j = i + 1; j < sortArray.Length; j++)
     {
             if (sortArray[j] < sortArray[i])    // problem with this test
             {
                           int temp = sortArray[i];   // swap ith and jth entries
                           sortArray[i] = sortArray[j];
                           sortArray[j] = temp;
             }
     }
}

class Employee
{
     private string name;
     private decimal salary;

     public Employee(string name, decimal salary)
     {
             this.name = name;
             this.salary = salary;
     }

     public override string ToString()
     {
             return string.Format(name + ", {0:C}", salary);
     }
     public static bool RhsIsGreater(object lhs, object rhs)
     {
             Employee empLhs = (Employee) lhs;
             Employee empRhs = (Employee) rhs;
             return (empRhs.salary > empLhs.salary) ? true : false;
     }
}




                                                    ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                           83

        BubbleSorter Example

BubbleSorter
Elmer Fudd, $10,000.00
Bugs Bunny, $20,000.00
Foghorn Leghorn, $23,000.00
Daffy Duck, $25,000.00
RoadRunner, $50,000.00
Wiley Coyote, $1,000,000.38




                ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              84

           Multicast Delegates

delegate void DoubleOp(double value);
//   delegate double DoubleOp(double
  value);   // can't

  class MainEntryPoint
  {
     static void Main()
     {
         DoubleOp operations = new
 DoubleOp(MathOperations.MultiplyByTwo);
         operations += new
 DoubleOp(MathOperations.Square);
                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             85

          Multicast Delegates

DoubleOp operation1 = new
  DoubleOp(MathOperations.MultiplyBy
  Two);
DoubleOp operation2 = new
  DoubleOp(MathOperations.Square);
DoubleOp operations = operation1 +
  operation2;




                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                            86

                    Multicast Delegates
class MathOperations
{
   public static void MultiplyByTwo(double value)
   {
         double result = value*2;
         Console.WriteLine("Multiplying by 2: {0} gives {1}", value,
   result);
   }
   public static void Square(double value)
   {
         double result = value*value;
         Console.WriteLine("Squaring: {0} gives {1}", value, result);
   }
}

static void ProcessAndDisplayNumber(DoubleOp action, double
   valueToProcess)
{
   Console.WriteLine("\nProcessAndDisplayNumber called with value = " +
valueToProcess);
   action(valueToProcess);
}




                                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                87

             Multicast Delegates

static void Main()
{
  DoubleOp operations = new
  DoubleOp(MathOperations.MultiplyByTwo);
  operations += new
  DoubleOp(MathOperations.Square);

    ProcessAndDisplayNumber(operations,
    2.0);
    ProcessAndDisplayNumber(operations,
    7.94);
    ProcessAndDisplayNumber(operations,
    1.414);
    Console.WriteLine();
}
                     ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  88

             Multicast Delegates

MulticastDelegate

ProcessAndDisplayNumber called with value = 2
Multiplying by 2: 2 gives 4
Squaring: 2 gives 4

ProcessAndDisplayNumber called with value = 7.94
Multiplying by 2: 7.94 gives 15.88
Squaring: 7.94 gives 63.0436

ProcessAndDisplayNumber called with value = 1.414
Multiplying by 2: 1.414 gives 2.828
Squaring: 1.414 gives 1.999396



                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                 89

                    Events

• The Receiver's View of Events
• Generating Events




                      ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                             90

     The Receiver's View of Events

btnOne.Click += new
  EventHandler(Button_Click);

btnOne.Click += new
  EventHandler(Button_Click);
btnTwo.Click += new
  EventHandler(Button_Click);

private void Button_Click(object
  sender, EventArgs e) { }

                  ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                              91

      The Receiver's View of Events

if(((Button)sender).Name == "btnOne")
  lblInfo.Text = "Button One was pressed";
else
  lblInfo.Text = "Button Two was pressed";

btnOne.Click += new
  EventHandler(Button_Click);
btnTwo.Click += new
  EventHandler(Button_Click);
btnTwo.Click += new
  EventHandler(btnTwo_Click);


                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  92

        The Receiver's View of Events

private void btnTwo_Click(object sender,
  EventArgs e) {
  MessageBox.Show("This only happens in Button 2
  click event");
}

btnOne.Click += new EventHandler(lblInfo.Text =
  "Button One was pressed";);
btnTwo.Click += new EventHandler(lblInfo.Text =
  "Button Two was pressed";);
btnTwo.Click += new EventHandler(MessageBox.Show
("This only happens in Button 2 click event"););




                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            93

          Generating Events

public delegate void
  ActionEventHandler(object sender,
  ActionCancelEventArgs ev);
public static event
  ActionEventHandler Action;




                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                          94

                    Generating Events
public class ActionCancelEventArgs :
   System.ComponentModel.CancelEventArgs
{
   string _msg = "";

    public ActionCancelEventArgs()            : base()                    {}

    public ActionCancelEventArgs(bool cancel) : base(cancel)                                                         {}

    public ActionCancelEventArgs(bool cancel, string message) :
    base(cancel)
    {
         _msg = message;
    }

    public string Message
    {
         get {return _msg;}
         set {_msg = value;}
    }
}

                               ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                            95

          Generating Events

ActionCancelEventArgs ev = new
  CancelEventArgs();
Action(this, ev);

protected void OnAction(object
  sender, ActionCancelEventArgs ev)
{
  if(Action != null)
     Action(sender, ev);
}

                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                                                         96

                                    Generating Events
using System;
using System.IO;
using System.ComponentModel;

namespace SimpleEvent
{
public class BusEntity
{

string _time = "";

public BusEntity()
{
Form1.Action += new Form1.ActionEventHandler(Form1_Action);
}

private void Form1_Action(object sender, ActionCancelEventArgs ev)
{
ev.Cancel = !DoActions();
if(ev.Cancel)
ev.Message = "Wasn't the right time.";
}

private bool DoActions()
{
bool retVal = false;
DateTime tm = DateTime.Now;

if(tm.Second < 30)
{
_time = "The time is " + DateTime.Now.ToLongTimeString();
retVal = true;
}
else
_time = "";

return retVal;

}

public string TimeString
{
get {return _time;}
}
                                                              ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
}
                                                                                                                              97

            Generating Events

private void btnRaise_Click(object sender,
  EventArgs e)
{
  ActionCancelEventArgs cancelEvent = new
  ActionCancelEventArgs();
  OnAction(this, cancelEvent);
  if(cancelEvent.Cancel)
     lblInfo.Text = cancelEvent.Message;
  else
     lblInfo.Text = _busEntity.TimeString;
}


                   ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                            98

                           Summary

• This chapter gave you the basics of delegates and events. You
  learned how to declare a delegate and add methods to the delegate
  list. You also learned the process of declaring event handlers to
  respond to an event, as well as how to create a custom event and
  use the patterns for raising the event.
• As a .NET developer, you will be using delegates and events
  extensively, especially when developing Windows Forms
  applications. Events are the means that the .NET developer has to
  monitor the various Windows messages that occur while the
  application is executing. Otherwise you would have to monitor the
  WndProc and catch the WM_MOUSEDOWN message instead of
  getting the mouse Click event for a button.
• The use of delegates and events in the design of a large application
  can reduce dependencies and the coupling of layers. This allows
  you to develop components that have a higher reusability factor.



                                 ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University
                                                                                                                                  99

     Memory Management and Pointers

• How the runtime allocates space on the stack
  and the heap
• How garbage collection works
• How to use destructors and the
  System.IDisposable interface to ensure
  unmanaged resources are released correctly
• The syntax for using pointers in C#
• How to use pointers to implement high-
  performance stack-based arrays


                       ZHANG Yu, Intelligence Engineering Lab at College of Computer Science and Technology in Jllin University

								
To top