Monday, 20 August 2007

70-536 - Ch1 - Lesson 1 - Using Value types.

  • .NET Framework (.NF) - an integral Windows component.
  • Value types (VT) - simplest types in .NF.
  • Contain their data directly - no ref to data stored elsewhere.
  • Instances of VT stored on stack.
  • 3 general VTs: built-in types, user-defined types, enumerations. Each is derived from System.ValueType.

Built-in VTs

  • Base types, provided by .NF. Other types are built from these.
  • Optimizing performance - runtime optimizes perf. of Int32 & UInt32. For F.P use Double.
  • VTs function as objects - you can call methods on them (e.g. ToString() ).
  • In .NT, all types are derived from System.Object.

Declaring VTs

  • declare symbol as instance of that type.
  • VTs - implicit constructor - declaring them instantiates the type automatically. (No ''new' keyword).
  • Constructor assigns a default value to new instance (e.g. o or null).
  • Best practice - explicitly initialize within declaration - bool b = false;
  • C# is case-sensitive.
  • Nullable - new type in .NF 2.0 - allows one to determine whether a value has been assigned or not.
  • Nullable b = null;
  • Shorthand - bool? b = null;
  • HasValue and Value members - if (b.HasValue) ... else ...;

Creating User-Defined Types

  • UDFs - structures/structs.
  • structs - composite of other types - easier to work with related data.
  • example - System.Drawing.Point.
  • explicit construction - System.Drawing.Point p = new System.Drawing.Point(2,3);
  • define own structures ~ struct keyword.
  • Class/Struct - former created on heap & is ref type, latter created on stack & is VT.

Creating Enumerations

  • Enums - related symbols that have fixed values.
  • Use to provide a list of choices to developers using your class.
  • E.g. - enum Titles : int { Mr, Ms, Mrs, Dr };
  • Use when developers consuming your types must choose from a limited set of choices for a value.

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

Structs

  • struct - UDT. A lightweight class.
  • similar - constructors, methds, fields, properties, operators,...
  • diffs - dont support inheritance (cant inherit from any other class + implicitly sealed), or destructors. Class ref type, struct VT.
  • structs - use only for types that are small, simple, and similar in behaviour and characteristics to built-in types.
  • structs - > efficient in arrays, <>
  • structs - can implement mult. interfaces.
  • diffs - no custom default (i.e parameterless) constructor. Also cannot init. an instance fld in a struct (e.g. private int xVal = 50; )
  • structs - can create without 'new' - though not recommended - more difficult to read.
  • struct - override ToString() - prevents boxing. (e.g. when passing -> WriteLine() ).

No comments: