Types and Members

Lesson1

Using Data Types

  • Store and represent data in app

    • Integer types - byte, short, int, long, sbyte, ulong, uint, ulong
    • Floating point - float, double, decimal (latter = for financial apps, can't hold as large a number as double but more accurate - 28 significant digits)
    • Boolean - true or false
    • Char - single Unicode character
    • String - reference to series of Chars
    • Object - super-type of all others. Can assign any object or variable to it. Requires explicit conversion to gain access to stored objects functionality
  • .NET languages strongly typed

    • Objects one type can't be freely exchanged with another
    • Parms in method calls must be of correct type
  • Implicit conversion when conversion can be performed without data lossFromTo
    byteshort, ushort, int, uint, ulong, float, double, decimal
    shortint, long, float, double, decimal
    intlong, float, double, decimal
    longfloat, double, decimal
    floatdouble
    charint, uint, long, ulong, float, double, decimal
    sbyteshort, int, long, ulong, float, double, decimal
    ushort  int, uint, long, ulong, float, double, decimal
    uintlong, ulong, float, double, decimal
    ulongfloat, double, decimal
  • Explicit conversion, or cast, where data loss possible. Only use where absolutely necessary. Provide system for handling failed casts
int anInteger = 10000;

short aShort;

aShort = (short) anInteger;

Data Type Functionality

  • All data types have built-in functionality. Minimum (from object type):

    • Equeals - are 2 instances equal
    • GetHashCode - Generate hash code
    • GetType - returns object type
    • ToString - human readable form of object
  • Small data types support this functionality via boxing
    • Implicit conversion of value types to reference types
    • Each class derives from object and can be implicitly converted to it
    • When call one of above methods the run-time creates temporary reference to object
    • Can manually box value types
int I = 100;

object O;

O = I;
  • Unboxing = explicit conversion of boxed variable back to value type
  • Data types also have methods not derived from object - usually functionality specific to that type
    • Parse - create value from string. Supported by all value types. Implemented as static (call from type, not instance)
string S = "1234";

int I = int.Parse(S);
  • String manipulation keenly important
  • string class exposes variety of methods, divided between instance and static methods
NameDescription
String.InsertInsert specified string into instance
String.PadLeft, String.PadRightAdd chars to left or right of instance
String.RemoveDelete specified number chars from string
String.ReplaceReplace occurrences of char in string
String.SplitReturn substrings delimited by specific char
String.SubstringReturn substring from string
String.ToCharArayReturns arrays of chars making up string
String.ToLower, String.ToUpperConvert string to lower or upper case
String.TrimEnd, String.TrimStart, String.Trim  Remove trailing or leading characters

 

NameDescription
String.Compare  Compare two string objects
String.ConcatConcatenate two+ strings
String.FormatFormat a string
String.JoinConcatenate array of strings with specified separator strings

 

Lesson 2

Constants

  • Refer to frequently used values by friendly names
  • Can not be changed or redefined once set
  • Use const keyword
  • Can be any intrinsic or enum type, not user-defined or array
public const double Pi = 3.14159265;

Enums

  • Work with related sets of constants
  • Associate memorable names with constants
public enum DaysOfWeek
{
 Monday = 1,
 Tuesday = 2,
 Wednesday = 3,
 Thursday = 4,
 Friday = 5,
 Saturday = 6,
 Sunday = 7
}
  • Default type = int - but can be any integral type (byte, short, int, long), specify in declaration line
public enum DaysOfWeek : byte
{
...
}
  • Not necessary to specify values for members, by default number incrementally from 0
  • Must explicitly convert enums to desired integral type
Public enum Numbers
{
 zero,
 one,
}

MessageBox.Show((int)Numbers.two * 2).ToString()); // Display 4
  • Can create methods accepting enums as values - code less prone to errors from inaccurate typing
public void ScheduleDayOff( DaysOfWeek day )
{
 switch( day )
 {
  ...
 }
} 

Arrays

  • Manage groups of similarly typed values or objects, referred to by index
  • Array declaration
int[] myIntegers;
  • Array initialisation
myIntegers = new int[32];
  • In one line
int[] myIntegers = new int[32];
  • Change size at runtime by redefining it - note contents will be lost
int[] myIntegers = new int[32];

myIntegers = new int[45];
  • Array of reference types, declaring and initialising creates array of null references. Must assign object to each entry
  • Rectangular arrays = each member of each dimension extended in each other dimension by same length, e.g. 2D array resembles a table
// Declare 5 by 3 array
int[,] intArray = new int[5,3];

// Decalre 2D array and set initial values
int[,] intArray2 = {{1,2,3},{4,5,6}};

// Declare cubic array
int[,,] cubeArray = {{7,2},{1,4},{3,5}};
  • Jagged array = array of arrays, e.g. 2D array is table where each row has different number columns
string[][] Families = new string[3][];

Families[0] = new string[] {"Smith", "Mum", "Dad", "Uncle Phil"};

Families[1] = new string[] {"Jones", "Mum", "Dad", "Suzie", "Bobby"};

Families[2] = new string[] {"Williams", "Earl", "Bob"};

Collections

  • Organises and exposes group of objects
  • Access by index
  • Dynamic resizing
  • Addition / removal of members at run time

    ClassDescription
    ArrayListArray of objects
    BitArrayCompact arrays of bits (0 and 1)
    CollectionBase  Base for implementing own collection class
    HashtableKey-value pairs organised by hashed key
    QueueFIFO group of objects
    SortedListAccess objects by index or key
    StackFILO group of objects z

 

  • Example using ArrayList:
// Create ArrayList
System.Collections.ArrayList myList = new System.Collections.ArrayList;

//Add item
Widget myWidget = new Widget;
myList.Add(myWidget);

// Access item using indexer (note ArrayList is zero-based)
object myObject;
myObject = myList[0];

// Indexer always returns objects. To obtain reference to same type as stored must cast
Widget aWidget;
aWidget = (Widget) myList[0];

// Remove uses reference to object
Widget anotherWidget = new Widget();
myList.Add(anotherWidget);
myList.Remove(anotherWidget);

// RemoveAt uses indexer
myList.RemoveAt(0);

// Count property is number of items in collection (as array zero based the value returned in one more than upper bound)

int arraySize = myList.Count;
  • Enumerating collection
    • Use foreach statement
    • All collection members should be of same type
    • If member can not be converted to foreach type get error
    • To work with collections of disparate types use object
    • foreach returns reference - i.e. can not modify collection entry. To do this use for...next
int[] myArray = new int[] {1,2,3,4,5};

for(int x=0; x <= myArray.GetUpperBound(0), x++)
{
  myArray[x]++;

  MessageBox(myArray[x].ToString());
}

Lesson 3

Implementing Properties

  • Expose member values / objects in more robust way than fields
  • Specialist method that looks like field, value set and got like fields
textBox1.Text = "Text property";

string myString;

myString = textBox1.Text;
  • Properties have 2 special methods, get and set
private string theText;

public string myText
{
 get
 {
  return theText;
 }

 set
 {
  theText = value;
 }
}
  • value = special keyword of set. Represents value to which property is set
  • key advantage = provide additional code to perform calculations / validation

Read Only Properties

  • Only provide get method
  • Private variable holding value marked with readonly keyword
private readonly int theInt;

public int InstanceNumber
{
 get
 {
  return theInt;
 }
}

Write Only Properties

  • Used infrequently, e.g. control localisation of form
  • Only provide set method
  • Private variable holding value declared as usual (i.e. no special keyword)

Indexer

  • Specialist property allowing group of objects to be exposed on name of object
  • Indexer identified by this
private int[] IntArray;

public int this [int index]
{
 get
 {
  return IntArray[index];
 }

 set
 {
  Intarray[index] = value;
 }
}

Collection Properties

  • Expose undetermined number objects of same type
  • Permits control of access to subordinate objects
  • Return the collection, usually exposed as read-only to control update as collection will store objects of any type
private readonly System.Collections.ArrayList myWidgets = new System.Collections.ArrayList();

public System.Collections.ArrayList Widgets
{
 get
 {
  return myWidgets;
 }
}
  • Wrap collection in property, providing conversion and validation code in accessor. Implement as indexer, or pair of methods (C# does not support parameterised properties)
private System.Collections.ArrayList myWidgets = new System.Collections.ArrayList ();

public Widget GetWidget(int I)
{
 return (Widget)myWidgets[I];
}

public void SetWidget(int I, Widget Wid)
{
 myWidgets[I] = Wid;
}
  • Implement own strongly typed collection - derive from System.Collections.CollectionBase. Expose collection directly and ensure only objects of specified type are added

Lesson 4

Delegates and Events

  • Event = message indicating interesting occurring in another part of app
  • EventHandler responds to event
  • EventHandler has same signature as event itself
  • Event handled by 1+ EventHandlers
  • Eventhandler handles 1+ events

Delegates

  • Type safe function pointer
  • Permits passing of entry point for method or invoke method without making explicit method call
  • Declare delegate specify signature of method it can call and return type. Following used to invoke methods that return int and take double as parameter:
public delegate int myDelegate(double D);

// Target method for delegate

public int ReturnInt(double D)
{

}

// Create instance of myDelegate
public void aMethod()
{
 myDelegate aDelegate = new myDelegate(ReturnInt);
}

// Use delegate to invoke method

aDelegate(12345);

Declaring and Raising Events

  • Directly tied to delegates
  • Can use access modifiers (public, private, protected)
// Declare delegate and event
public delegate void calculateDelegate(double D);
public event calculationDelegate CalculationComplete;

// Raise event
CalculationComplete(66532);

Event Handlers

  • Once event declared must be associated with event handler prior to being raised otherwise error occurs
  • Both instance and static events can exist
  • Can return value (like any other function)
  • Use += to associate event with delegate instance
// Assume existence of method DisplayResults with signature appropriate for calculationDelegate.

// Create new delegate to create the association.
Account.CalculationComplete += new calculationDelegate(DisplayResults);

// Create association with existing delegate
CalculationDelegate calc = new calculationDelegate(DisplayResults);

Account.CalculationComplete += calc;
  • Default delegates provided for .NET Framework base class library events
  • To manually add event handler no need to declare new delegate. Create new instance of predefined default delegate
// System.EventHandler is delegate for most controls in System.windows.Formds namespace. Designate event handler for Click event of control called button1

button1.Click += new System.EventHandler(clickHandler);
  • Remove event handler with -= operator. May want to do this if want event handler to only be called once.
// Remove association between Account.CalculationComplete and DisplayResults method

Account.CalculatioComplete -= new CalculationDelegate(DisplayResults);
  • Event handlers can be associated with multiple events, e.g. single method handles click event for number of buttons. Method distinguishes between source using sender parameter
Button1.Click += new System.EventHandler(ClickHandler);

Button2.Click += new System.EventHandler(ClickHandler);
  • Events can be processed by multiple handlers. Order of handler invocation determined by order of association. Value retuned by event is that of the last method executed.

Download