    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: An Overview of C#.NET</title>
        <link>https://members.accu.org/index.php/articles/395</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #49 - Jun 2002</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c196/">49</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-196/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+196/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;An Overview of C#.NET</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 26 June 2002 17:46:10 +01:00 or Wed, 26 June 2002 17:46:10 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e18" id="d0e18"></a></h2>
</div>
<p>.NET rests on the Common Language Infrastructure (CLI).
Microsoft, Intel, and Hewlett-Packard have jointly submitted the
CLI as an ECMA standard. The CLI is designed for strongly typed
languages and the CLI proposal has 5 partitions. Part 1 specifies
the CLI foundation: the CTS, the VES, and the CLS. The Common Type
System (CTS) specifies two CLI fundamental types: value types and
reference types. Compiling a C# program does not create a regular
executable file. Instead it creates a program in Common
Intermediate Language (CIL, specified in partition 3). A compiled
C# program also contains a block of metadata (data about the
program itself) called a manifest (specified in partition 2). This
metadata allows reflection and effectively eliminates the need for
the registry. The job of the Virtual Execution System (VES) is to
translate the CIL into native executable code (which can be done
just-in-time or at installation). The Common Language Specification
(CLS) is a set of rules designed to allow language
interoperability. For example, unsigned integer types are
<span class="emphasis"><em>not</em></span> in the CLS so your C#
modules must not expose unsigned integers if you want them to be
fully interoperable.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e25" id="d0e25"></a>Hello
World</h2>
</div>
<p>The obligatory console Hello World in C# looks like this.</p>
<pre class="programlisting">
class HelloWorld {
  static void Main() {
    System.Console.WriteLine(
                        &quot;Hello, world!&quot;);
  }
}
</pre>
<p>C# has a sensibly limited preprocessor. There are no macro
functions. What you see is what you get. A C# source file is not
required to have the same name as the class it contains.
Identifiers should follow the camelCasing or PascalCasing notation
depending on whether they are private or non-private respectively.
Hungarian notation is officially <span class=
"emphasis"><em>not</em></span> recommended. C# is a case sensitive
language so Main must be spelled with a capital M. A C# program
exposing two identifiers differing only in case is not CLS
compliant. The CLS supports exception handling and C# accesses
these features using the try/catch/finally keywords. Exceptions are
used extensively in the .NET framework classes. C# also supports
C++ like namespaces as a purely logical scoping/naming mechanism.
You can write using directives to bring the typenames in a
namespace into scope.</p>
<pre class="programlisting">
using System; // System.Exception

class HelloWorld {
  static void Main() {
    try {
      NotMain()
    }
    catch (Exception caught) {
      ...
    }
  }
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e39" id="d0e39"></a>C#
Fundamentals</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e42" id="d0e42"></a>Numeric Types</h3>
</div>
<p>C# supports 8 integer types (not all of which are CLS compliant)
and three floating point types. The floating point literal suffixes
for these three types are F/f, D/d, and M/m (think m for
money).</p>
<div class="figure"><a name="d0e47" id="d0e47"></a>
<div class="mediaobject c2"><img src="/var/uploads/journals/resources/IntegerTypes.png"
align="middle" alt="C# Integer Types"></div>
<p class="title c3">Figure 1. C# Integer Types</p>
</div>
<p>C# expressions follow the standard C/C++/Java rules of
precedence and associativity. As in Java, the order of operand
evaluation is left to right (in C/C++ it's unspecified), an
expression must have a side effect (in C/C++ it needn't) and a
variable can only be used once it has definitely been assigned (not
true in C/C++).</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e55" id="d0e55"></a>Checked
Arithmetic</h3>
</div>
<p>The CLS allows expressions or statements that contain integer
arithmetic to be checked to detect integer overflow. C# uses the
checked and unchecked keywords to access this feature. An integer
overflow throws an <tt class="exceptionname">OverflowException</tt>
when checked. (Integer division by zero <span class=
"emphasis"><em>always</em></span> throws a <tt class=
"exceptionname">DivideByZeroException</tt>.) Floating point
expressions never throw exceptions (except when being cast to
integers). For example:</p>
<pre class="programlisting">
class Overflow {
  static void Main() {
    try {
      int x = int.MaxValue + 1;
      // wraps to int.MinValue
      int y = checked(int.MaxValue + 1);
      // throws
    }
    catch (System.OverflowException
                                caught) {
      System.Console.WriteLine(caught);
    }
  }
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e71" id="d0e71"></a>Control Flow</h3>
</div>
<p>C# supports the <tt class="literal">if</tt>/<tt class=
"literal">while</tt>/<tt class="literal">for</tt>/<tt class=
"literal">do</tt> statements familiar to C/C++/Java programmers. As
in Java, a C# boolean expression must be a genuine boolean
expression. There are <span class="emphasis"><em>never</em></span>
any conversions from a built in type to <tt class=
"literal">true</tt>/<tt class="literal">false</tt>. A variable
introduced in a <tt class="literal">for</tt> statement
initialization is scoped to that for statement. C# supports a
<tt class="literal">foreach</tt> statement, which you can use to
effortlessly iterate through an array (or any type that supports
the correct interface).</p>
<pre class="programlisting">
class Foreach {
  static void Main(string[] args) {
    foreach (string arg in args) {
      System.Console.WriteLine(arg);
    }
  }
}
</pre>
<p>The C# switch statement does not allow fall-through behavior.
Every <tt class="literal">case</tt> section (including the optional
<tt class="literal">default</tt> section) must end in a <tt class=
"literal">break</tt> statement, a <tt class="literal">return</tt>
statement, a <tt class="literal">throw</tt> statement, or a
<tt class="literal">goto</tt> statement. You are only allowed to
switch on integral types, bools, chars, strings and enums (these
types all have a literal syntax).</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e125" id="d0e125"></a>Methods and
Parameters</h3>
</div>
<p>C# does not allow global methods; all methods must be declared
within a struct or a class. C# does not have a C/C++ header/source
file separation; all methods must be declared inline. Arguments can
be passed to methods in three different ways:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><tt class="literal">copy</tt>. The parameter is a <span class=
"emphasis"><em>copy</em></span> of the argument. The argument must
be definitely assigned. The method cannot modify the argument.</p>
</li>
<li>
<p><tt class="literal">out</tt>. The parameter is an <span class=
"emphasis"><em>alias</em></span> for the argument. The argument
need not be definitely assigned. The method must definitely assign
the parameter/argument.</p>
</li>
<li>
<p><tt class="literal">ref</tt>. The parameter is again an
<span class="emphasis"><em>alias</em></span> for the argument. The
argument must be definitely assigned. The method is not required to
assign the parameter/argument.</p>
</li>
</ul>
</div>
<p>The ref/out keywords must appear on the method declaration and
the method call. For example:</p>
<pre class="programlisting">
class Calling {
  static void Copies(int param) { ... }
  static void Modifies(out int param)
                                { ... }
  static void Accesses(ref int param)
                                { ... }
  static void Main() {
    int arg = 42;
    Copies(arg); // arg won't change
    Modifies(out arg); // arg will change
    Accesses(ref arg);
                 // arg might change
  }
}
</pre>
<p>C# supports method overloading but not return type covariance.
Unlike Java, C# does <span class="emphasis"><em>not</em></span>
support method throw specifications (all exceptions are effectively
unchecked).</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e164" id="d0e164"></a>Value
Types</h2>
</div>
<p>C# makes a clear distinction between value types and reference
types. Value type instances (values) live on the stack and are used
directly whereas reference type instances (objects) live on the
heap and are used indirectly. C# has excellent language support for
declaring user-defined value types (unlike Java which has
none).</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e169" id="d0e169"></a>Enums and
Structs</h3>
</div>
<p>You can declare <tt class="literal">enum</tt> types in C#. For
example:</p>
<pre class="programlisting">
enum Suit {Hearts, Clubs, Diamonds, Spades}
</pre>
<p>You can also declare a user-defined value type using the
<tt class="literal">struct</tt> keyword. For example:</p>
<pre class="programlisting">
struct CoOrdinate {
  int x, y;
}
</pre>
<p>Unlike C++, the default accessibility of <tt class=
"literal">struct</tt> fields is private. You control the
initialization of <tt class="literal">struct</tt> values using
constructors. You use the <tt class="literal">static</tt> keyword
to declare shared methods and shared fields. The <tt class=
"literal">readonly</tt> keyword is used for fields that can't be
modified and are initialised at runtime. The <tt class=
"literal">const</tt> keyword is used for fields (and local
variables) that can't be modified and are initialised at compile
time (and is therefore restricted to <tt class="literal">enum</tt>s
and built in types). As in Java, each declaration must repeat its
access specifier.</p>
<pre class="programlisting">
struct CoOrdinate {
  public CoOrdinate(int initialX,
                    initialY) {
    x = rangeCheckedX(initialX);
    y = rangeCheckedY(initialY);
  }
  public const int MaxX = 600;
  public static readonly CoOrdinate
            Empty = new CoOrdinate(0, 0);
  ...
  private int x, y;
}
</pre>
<p>The built in value type keywords are in fact just a notational
convenience. The keyword <span class="structname">int</span> (for
example) is an alias for <span class=
"structname">System.Int32</span>, a <tt class="literal">struct</tt>
called <span class="structname">Int32</span> that lives in the
<tt class="literal">System</tt> namespace. Whether you use
<span class="structname">int</span> or <span class=
"structname">System.Int32</span> in a C# program makes no
difference.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e231" id="d0e231"></a>Operator
Overloading</h3>
</div>
<p>C# supports operator overloading. <tt class="literal">Enum</tt>
types automatically support most operators but <tt class=
"literal">struct</tt> types do not. For example, to allow
<tt class="literal">struct</tt> values to be compared for
equality/inequality you must write == and != operators:</p>
<pre class="programlisting">
struct CoOrdinate {
  public static bool operator==(
        CoOrdinate lhs, CoOrdinate rhs) {
    return lhs.x == rhs.x &amp;&amp;
           lhs.y == rhs.y;
  }
  public static bool operator!=(
        CoOrdinate lhs, CoOrdinate rhs) {
    return !(lhs == rhs);
  }
  ...
  private int x, y;
}
</pre>
<p>Operators must be public static methods. Operator parameters can
only be passed by copy (no <tt class="literal">ref</tt> or
<tt class="literal">out</tt> parameters). One or more of the
operator parameter types must be of the containing type so you
can't change the meaning of the built in operators. The increment
(and decrement) operator can be overloaded and works correctly when
used in either prefix and postfix form. C# also supports conversion
operators which must be declared using the implicit or explicit
keyword. Some operators (such as simple assignment) cannot be
overloaded.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e255" id="d0e255"></a>Properties</h3>
</div>
<p>Rather than using a Java Bean like naming convention, C# uses
properties to declare read/write access to a logical field without
breaking encapsulation. Properties contain only get and set
accessors. The get accessor is automatically called in a read
context and the set accessor is automatically called in a write
context. For example (note the x and X case difference):</p>
<pre class="programlisting">
struct CoOrdinate {
  ...
  public int X {
    get { return x; }
    set { x = rangeCheckedX(value); }
  }
  ...
  private static int
            rangeCheckedX(int argument) {
    if(argument &lt; 0 || argument &gt; MaxX) {
      throw new ArgumentOutOfRange(&quot;X&quot;);
    }
    return argument;
  }
  ...
  private int x, y;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e262" id="d0e262"></a>Indexers</h3>
</div>
<p>An indexer is an operator like way to allow a user-defined type
to be used as an array. An indexer, like a property, can contain
only get/set accessors. For example:</p>
<pre class="programlisting">
struct Matrix {
  ...
  public double this [ int x, int y ] {
    get { ... }
    set { ... }
  }
  public Row this [ int x ] {
    get { ... }
    set { ... }
  }
  ...
}
</pre></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e269" id="d0e269"></a>Reference
Types</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e272" id="d0e272"></a>Classes</h3>
</div>
<p>Classes allow you to create user-defined reference types. One or
more reference type variables can easily refer to the same object.
A variable whose declared type is a class can be assigned to
<tt class="literal">null</tt> to signify that the reference does
not refer to an object (struct variables cannot be assigned to
<tt class="literal">null</tt>). Assignment to null counts as a
Definite Assignment. Classes can declare constructors, destructors,
fields, properties, indexers, and operators. Despite identical
syntax, classes and structs have subtly different rules and
semantics. For example, you can declare a parameterless constructor
in a class but not in a struct. You can initialise fields declared
in a class at their point of declaration, but struct fields can
only be initialized inside a constructor. Here is a class called
<tt class="classname">MyForm</tt> that implements the GUI
equivalent of Hello World in C#.NET.</p>
<pre class="programlisting">
using System.Windows.Forms;
class Launch {
  static void Main() {
    Application.Run(new MyForm());
  }
}
class MyForm : Form {
  public MyForm() { Text = captionText; }
  private string captionText
                       = &quot;Hello, world!&quot;;
}
</pre>
<p>Variables whose declared type is a class can be passed by
<tt class="literal">copy</tt>, by <tt class="literal">ref</tt>, and
by <tt class="literal">out</tt> exactly as before.</p>
<pre class="programlisting">
class WrappedInt {
  public WrappedInt(int initialValue)
  { value = initialValue; }
  ...
  private int value;
}
class Calling {
  static void Copies(WrappedInt param)
    { ... }
  static void Modifies(out
               WrappedInt param) { ... }
  static void Accesses(ref
               WrappedInt param) { ... }
  static void Main() {
    WrappedInt arg = new WrappedInt(42);
    Copies(arg); // arg won't change
    Modifies(out arg); // arg will change
    Accesses(ref arg); // arg might change
  }
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e301" id="d0e301"></a>Strings</h3>
</div>
<p>C# string literals are double quote delimited (<span class=
"structname">char</span> literals are single quote delimited).
Strings are reference types so it is easy for two or more string
variables to refer to the same string object. The keyword
<tt class="classname">string</tt> is an alias for the <tt class=
"classname">System.String</tt> class in exactly the same way that
<span class="structname">int</span> is an alias for the
<span class="structname">System.Int32</span> struct.</p>
<pre class="programlisting">
namespace System {
  public sealed class String : ... {
    ...
    public static bool operator==(
          String lhs, String rhs) { ... }
    public static bool operator!=(
          String lhs, String rhs) { ... }
    ...
    public int Length { get { ... } }
    public char this[int index]
      { get { ... } }
    ...
    public CharEnumerator GetEumerator()
      { ... }
    ...
  }
}
</pre>
<p>The <tt class="classname">String</tt> class supports a readonly
indexer (it contains a <tt class="literal">get</tt> accessor but no
<tt class="literal">set</tt> accessor). The C# string type is an
immutable type (just like in Java). The string equality and
inequality operators are overloaded but the relational operators
(&lt; &lt;= &gt; &gt;=) are not. The <tt class=
"classname">StringBuilder</tt> class is the mutable companion to
string and lives in the <tt class="literal">System.Text</tt>
namespace. You can iterate through a string expression using a
foreach statement.</p>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e340" id="d0e340"></a>Arrays</h3>
</div>
<p>C# arrays are reference types. The size of the array is not part
of the array type. You can declare rectangular arrays of any rank
(Java supports only one dimensional rectangular arrays).</p>
<pre class="programlisting">
int[] row;
int[,] grid;
</pre>
<p>Array instances are created using the <tt class=
"literal">new</tt> keyword. Array elements are default initialised
to zero (<tt class="literal">enum</tt>s and numeric types),
<tt class="literal">false</tt> (bool), or <tt class=
"literal">null</tt> (reference types).</p>
<pre class="programlisting">
row = new int[42];
grid = new int[9,6];
</pre>
<p>Array instances can be initialised. A useful initialisation
shorthand does not work for assignment.</p>
<pre class="programlisting">
int[] row = new int[4]{1, 2, 3, 4};
                              // longhand
int[] row = { 1, 2, 3, 4 };  // shorthand
row = new int[4]{ 1, 2, 3, 4 };  // okay
row = {1, 2, 3, 4};  // compile time error
</pre>
<p>Array indexes start at zero and all array accesses are bounds
checked (<tt class="exceptionname">IndexOutOfRangeException</tt>).
All arrays implicitly inherit from the <tt class=
"classname">System.Array</tt> class. This class brings array types
into the CLR (Common Language Runtime) and provides some handy
properties and methods:</p>
<pre class="programlisting">
namespace System {
  public abstract class Array : ... {
    ...
    public int Length { get { ... } }
    public int Rank { get { ... } }
    public int GetLength(int rank) { ... }
    public virtual IEnumerator
    GetEnumerator() { ... }
    ...
  }
}
</pre>
<p>The element type of an array can itself be an array creating a
so called &quot;ragged&quot; array. Ragged arrays are not CLS compliant. You
can use a <tt class="literal">foreach</tt> statement to iterate
through a ragged array or through a rectangular array of any
rank:</p>
<pre class="programlisting">
class ArrayIteration {
  static void Main() {
    int[] row = { 1, 2, 3, 4 };
    foreach (int number in row) { ... }
    int[,] grid = { { 1, 2 }, { 3, 4 } };
    foreach (int number in grid) { ... }
    int[][] ragged = { new int[2]{1,2},
                   new int[4]{3,4,5,6} };
    foreach (int[] array in ragged) {
      foreach (int number in array) { ... }
    }
  }
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e384" id="d0e384"></a>Boxing</h3>
</div>
<p>An object reference can be initialised with a value. This does
not create a reference referring into the stack (which is just as
well!). Instead the CLR makes a copy of the value on the heap and
the reference refers to this copy. The copy is created using a
plain bitwise copy (guaranteed to never throw an exception). This
is called boxing. Extracting a boxed value back into a local value
is called unboxing and requires an explicit cast. When unboxing the
CLR checks if the boxed value has the exact type specified in the
cast (conversions are not considered). If it doesn't the CLR throws
an <tt class="exceptionname">InvalidCastException</tt>. C# uses
boxing as part of the params mechanism to create typesafe variadic
methods (methods that can accept a variable number of arguments of
any type).</p>
<pre class="programlisting">
struct CoOrdinate {
  ...
  private int x, y;
}
class Boxing {
  static void Main() {
    CoOrdinate pos;
    pos.X = 1;
    pos.Y = 2;
    object o = pos; // boxes
    ...
    CoOrdinate copy = (CoOrdinate)o;
                        // cast to unbox
  }
}
</pre>
<div class="figure"><a name="d0e394" id="d0e394"></a>
<div class="mediaobject c2"><img src="/var/uploads/journals/resources/Boxing.png" align=
"middle" alt="Boxing"></div>
<p class="title c3">Figure 2. Boxing</p>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e400" id="d0e400"></a>Type
Relationships</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e403" id="d0e403"></a>Inheritance</h3>
</div>
<p>C# supports the same single inheritance model as Java; a class
can extend at most one other class (in fact a class always extends
exactly one class since all classes implicitly extend <tt class=
"classname">System.Object</tt>). A struct cannot act as a base type
or be derived from. A derived class can access non-private members
of its immediate base class using the <tt class="literal">base</tt>
keyword. Unlike Java (and like C++) by default C# methods,
indexers, properties, and events are <span class=
"emphasis"><em>not</em></span> virtual. The <tt class=
"literal">virtual</tt> keyword specifies the <span class=
"emphasis"><em>first</em></span> implementation. The <tt class=
"literal">override</tt> keyword specifies <span class=
"emphasis"><em>another</em></span> implementation. The <tt class=
"literal">sealed</tt> <tt class="literal">override</tt> combination
specifies the last implementation.</p>
<pre class="programlisting">
class Token {
  ...
  public virtual CoOrdinate Location {
    get {
      ...
    }
  }
}
class LiteralToken : Token {
  ...
  public LiteralToken(string symbol) {
    ...
  }
  public override CoOrdinate Location {
    get {
      ...
    }
  }
}
class StringLiteralToken : LiteralToken {
  ...
  public StringLiteralToken(string
                 symbol) : base(symbol) {
    ...
  }
  public sealed override
                    CoOrdinate Location {
    get {
      ...
    }
  }
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e437" id="d0e437"></a>Interfaces</h3>
</div>
<p>C# interfaces contain only the names of methods. Method bodies
are not allowed. Access modifiers are not allowed (all methods are
implicitly public). Fields are not allowed (not even static ones).
Static methods are not allowed (so no operators). Nested types are
not allowed. Properties, indexers, and events (again with no
bodies) are allowed though. An interface, struct, or class can have
as many base interfaces as it likes.</p>
<pre class="programlisting">
interface IToken {
  ...
  CoOrdinate Location { get; }
}
</pre>
<p>A struct or class must implement all its inherited interface
methods. Interface methods can be implemented implicitly or
explicitly.</p>
<pre class="programlisting">
class LiteralToken : IToken {
  ...
  public CoOrdinate Location {
    // implicit implementation
    get {
      ...
    }
  }
}
class LiteralToken : IToken {
  ...
  CoOrdinate IToken.Location {
    // explicit implementation
    get {
      ...
    }
  }
}
</pre>
<p>You use the <tt class="literal">abstract</tt> keyword to declare
an abstract class or an abstract method (only abstract classes can
declare abstract methods). You use the <tt class=
"literal">sealed</tt> keyword to declare a class that cannot be
derived from. The inheritance notation is positional; base class
first, followed by base interfaces.</p>
<pre class="programlisting">
interface IToken {
  ...
  CoOrdinate Location {
    get;
  }
}

abstract class DefaultToken {
  ...
  protected DefaultToken(CoOrdinate
                               where) {
    location = where;
  }
  public CoOrdinate Location {
    get {
      return location;
    }
  }
  private readonly CoOrdinate location;
}

sealed class StringLiteralToken
                : DefaultToken, IToken {
  ...
}
</pre>
<p>Runtime type information is available via the <tt class=
"literal">is</tt>, <tt class="literal">as</tt>, and <tt class=
"literal">typeof</tt> keywords as well as the <tt class=
"methodname">object.GetType()</tt> method.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e472" id="d0e472"></a>Resource
Management</h2>
</div>
<p>You can declare a destructor in a class. A C# destructor has the
same name as its class, prefixed with a tilde (~). A destructor is
not allowed an access modifier or any parameters. The compiler
converts your destructor into an override of the <tt class=
"methodname">object.Finalize</tt> method. For example, this:</p>
<pre class="programlisting">
public class StreamWriter : TextReader {
  ...
  ~StreamWriter() {
    Close();
  }
  public override void Close() {
    ...
  }
}
</pre>
<p>is converted into this: (You can use the ILDASM tool to see this
transformation in CIL.)</p>
<pre class="programlisting">
public class StreamWriter : TextReader {
  ...
  protected override void Finalize() {
    try {
      Close();
    }
    finally {
      base.Finalize();
    }
  }
  public override void Close() {
    ...
  }
}
</pre>
<p>You are not allowed to call a destructor or the <tt class=
"methodname">Finalize</tt> method in code. Instead, the
generational garbage collector (which is part of the CLR) calls
<tt class="methodname">Finalize</tt> on objects sometime after they
become unreachable but definitely before the program ends. You can
force a garbage collection using the <tt class=
"methodname">System.GC.Collect()</tt> method. C# does not support
struct destructors (although CIL does). However, C# does have a
<tt class="literal">using</tt> statement which you can use to scope
a resource to a local block in an exception safe way. For example,
this:</p>
<pre class="programlisting">
class Example {
  void Method(string path) {
    using (LocalStreamWriter exSafe =
                new StreamWriter(path)) {
      StreamWriter writer =
                exSafe.StreamWriter;
      ...
    }
  }
}
</pre>
<p>is automatically translated into this:</p>
<pre class="programlisting">
class Example {
  void Method(string path) {
    {
      LocalStreamWriter exSafe =
                new StreamWriter(path);
      try {
        StreamWriter writer =
                exSafe.StreamWriter;
        ...
      }
      finally {
        exSafe.Dispose();
      }
    }
  }
}
</pre>
<p>which relies on <tt class="classname">LocalStreamWriter</tt>
implementing the <tt class="classname">System.IDisposable</tt>
interface:</p>
<pre class="programlisting">
public struct LocalStreamWriter
                          : IDisposable {
  public LocalStreamWriter(StreamWriter
                             decorated) {
    local = decorated;
  }

  public static implicit operator
       LocalStreamWriter(StreamWriter
                             decorated) {
    return new
            LocalStreamWriter(decorated);
  }

  public StreamWriter StreamWriter {
    get {
      return local;
    }
  }

  public void Dispose() {
    local.Close();
  }

  private readonly StreamWriter local;
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e516" id="d0e516"></a>Program
Relationships</h2>
</div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e519" id="d0e519"></a>Delegates and
Events</h3>
</div>
<p>The <tt class="literal">delegate</tt> is the last C# type. A
<tt class="literal">delegate</tt> is a named method signature
(similar to a function pointer in C/C++). For example, the
<tt class="literal">System</tt> namespace declares a <tt class=
"literal">delegate</tt> called <tt class=
"classname">EventHandler</tt> that's used extensively in the
<tt class="literal">Windows.Forms</tt> classes:</p>
<pre class="programlisting">
namespace System {
  public delegate void EventHandler(
        object sender, EventArgs sent);
  ...
}
</pre>
<p><tt class="classname">EventHandler</tt> is now a reference type
you can use as a field, a parameter, or a local variable. Calling a
<tt class="literal">delegate</tt> calls all the <tt class=
"literal">delegate</tt> instances attached to it.</p>
<pre class="programlisting">
namespace Not.System.Windows.Forms {
  public class Button {
    ...
    public EventHandler Click;
    ...
    protected void OnClick(EventArgs
                                 sent) {
      if (Click != null) {
        Click(this, sent); // call here
      }
    }
  }
}
</pre>
<p>All delegate types implicitly derive from the <tt class=
"classname">System.Delegate</tt> class. You use the <tt class=
"literal">event</tt> keyword to modify the declaration of a
delegate field. Event delegates can only be used in restricted,
safe ways (for example, you can't call the delegate from outside
its class):</p>
<pre class="programlisting">
namespace System.Windows.Forms {
  public class Button {
    ...
    public event EventHandler Click;
  }
}
</pre>
<p>You create an instance of a delegate type by naming a method
with a matching signature and you attach a delegate instance to a
matching field using the += operator.</p>
<pre class="programlisting">
using System.Windows.Forms;

class MyForm : Form {
  ...
  private void initializeComponent() {
    ...
    okButton = new Button(&quot;OK&quot;);
    okButton.Click += new
    EventHandler(this.okClick);
    // create + attach
  }
  private void okClick(object sender,
                       EventArgs sent) {
    ...
  }
  ...
  private Button okButton;
}
</pre></div>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e570" id="d0e570"></a>Assemblies</h3>
</div>
<p>You can compile a working set of source files (all written in
the same supported language) into a .NET module. For example, using
the C# command line compiler:</p>
<pre class="screen">
csc /target:module /out:ratio.netmodule *.cs
</pre>
<p>The default file extension for a .NET module is <tt class=
"literal">.netmodule</tt>. A .NET module contains types and CIL
instructions directly and forms the smallest unit of dynamic
download. However, a .NET module cannot be run. The only thing you
can do with a .NET module is add it to an assembly. An assembly
contains a manifest (a module does not). The manifest is metadata
that describes the contents of the assembly and makes the assembly
self describing. An assembly knows:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>the assembly identity</p>
</li>
<li>
<p>any referenced assemblies</p>
</li>
<li>
<p>any referenced modules</p>
</li>
<li>
<p>types and CIL code held directly</p>
</li>
<li>
<p>security permissions</p>
</li>
<li>
<p>resources (eg bitmaps, icons)</p>
</li>
</ul>
</div>
<p>You create a .NET DLL (an assembly) using the /target:library
option from the command line compiler (there are various other
options for adding modules and referencing other assemblies):</p>
<pre class="screen">
csc /target:library /out:ratio.dll *.cs
</pre>
<p>You create a .NET EXE (an executable assembly) using the
<tt class="literal">/target:exe</tt> options on the command line
compiler (one of the structs/classes must contain a <tt class=
"methodname">Main</tt> method).</p>
<pre class="screen">
csc /target:exe /out:ratio.exe *.cs
</pre>
<p>Assemblies come in two forms. A private assembly is not
versioned, and is used only by a single application. A shared
assembly is versioned, and lives in a special shared directory
called the Global Assembly Cache (GAC). Shared assembly version
numbers are created using an IP like numbering scheme:</p>
<pre class="programlisting">
&lt;major&gt; . &lt;minor&gt; . &lt;build&gt; . &lt;revision&gt;
</pre>
<p>Shared applications that differ only by version number can
coexist in the GAC (this is called side-by-side execution). The
particular version of an assembly that an individual application
uses when running can be controlled from an XML file. For
example:</p>
<pre class="programlisting">
...
&lt;BindingPolicy&gt;
  &lt;BindingRedir
    Name=&quot;ratio&quot; ...
    Version=&quot;*&quot;
    VersionNew=&quot;6.1.1212.14&quot;
    UseLatestBuildRevision=&quot;no&quot;/&gt;
&lt;/BindingPolicy&gt;
...
</pre>
<p>You can edit this config file to choose your binding policy. For
example:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Safe: exactly as built</p>
</li>
<li>
<p>Default: major.minor as built</p>
</li>
<li>
<p>Specific: major.minor as specified.</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e635" id=
"d0e635"></a>Attributes</h2>
</div>
<p>You use attributes to tag code elements with declarative
information. This information is added to the metadata, and can be
queried and acted upon at translation/run time using reflection.
For example, you use the <tt class="literal">[Conditional]</tt>
attribute to tag methods you want removed from the release build
(calls to conditional methods are also removed):</p>
<pre class="programlisting">
using System.Diagnostics;
  class Trace {
    [Conditional(&quot;DEBUG&quot;)]
    public static void Write(string
                               message) {
      ...
  }
}
</pre>
<p>You use the [<tt class="literal">CLSCompliant</tt>] attribute to
declare (or check) that a source file conforms to the Common
Language Specification:</p>
<pre class="programlisting">
using System;

[assembly:CLSCompliant(true)]
...
</pre>
<p>You can use the [<tt class="literal">MethodImpl</tt>] attribute
to synchronize a method:</p>
<pre class="programlisting">
using System.Runtime.CompilerServices;

class Example {
  [MethodImpl(MethodImplOptions.
                           Synchronized)]
  void SynchronizedMethod() {
    ...
  }
}
</pre>
<p>The attribute mechanism is extensible; you can easily create and
use your own attribute types:</p>
<pre class="programlisting">
public sealed class DeveloperAttribute
                 : Attribute {
  public DeveloperAttribute(string name) {
    ...
  }
}
...
[Developer(&quot;Jon Jagger&quot;)]
public struct LocalStreamWriter
                          : IDisposable {
  ...
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e663" id="d0e663"></a>Summary</h2>
</div>
<p>C# programs compile into Common Intermediate Language (CIL). CIL
types that conform to the CLS (Common Language Specification) can
be used by any .NET language. For example, the types in the System
namespace are implemented in the mscorlib.dll assembly. Programs
written in C#, in VB.NET, or in managed C++, can all use this
assembly (there isn't one version of the assembly for each
language).</p>
<p>CIL programs are translated into executable programs either at
installation time or just-in-time as they are executed by the VES
(Virtual Execution System). The CLI (Common Language Infrastructure
- the CTS, the VES, the CLS, and the metadata specification) is an
ECMA standard and efforts are already underway to implement the CLI
on non Windows platforms (eg <a href="http://www.go-mono.com"
target="_top">http://www.go-mono.com</a>).</p>
<p>C# is a modern general purpose programming language. It has
clear similarities to Java (reference types, inheritance model,
garbage collection) and to C++ (value types, operator overloading,
logical namespaces, by default methods are not virtual). It has no
backward compatibility constraints (as C++ does to C) and
avoids/resolves known problems in Java. The CTS (Common Type
System) makes a clear distinction between value types and reference
types. The more I use C# the more I like it and the more I
appreciate the careful and consistent decisions taken during its
design. C# is my language of choice for .NET development. In
roughly keeping to the allotted word count I have necessarily
omitted numerous important aspects of C#. Nevertheless I hope this
article has given you a flavour of C# and its relationship to
.NET.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
