.NET 2.0: Notes on Foundation Part 1

Nullable Type

In .NET 2.0, you can declare a variable as Nullable:

Nullable<bool> b = null;

// shorthand notation
bool? b = null;


String versus StringBuilder

Strings are immutable in .NET.  If you want to combine multiple strings, you can use String class’s Concat, Join, or Format methods or use StringBuilder class.



To declare, initialize and sort an array:

// Declare and initialize an array.
int[] arr = { 3, 1, 2 };

// Call a shared/static array method.

// Display the result.
Console.WriteLine("{0}, {1}, {2}", arr[0], arr[1], arr[2]);


Try/Catch/Finally Blocks

Use multiple Catch blocks to filter exceptions, ordered from most specific to least specific.  Make sure variables you want to access in the Finally block is declared outside of the Try block.  You can also use nested  Try/Catch/Finally blocks.


Commonly Used Interfaces

IComparable, IDisposable, IConvertible, ICloneable, IEquatable, and IFormattble are commonly used interfaces.



To declare a generic type:

class Gen<T, U>
  public T t;
  public U u;

  public Gen(T _t, U _u)
    t = _t;
    u = _u;

To consume a generic type:

// Add two strings using the Gen class
Gen<string, string> ga = new Gen<string, string>("Hello, ", "World!");
Console.WriteLine(ga.t + ga.u);

// Add a double and an int using the Gen class
Gen<double, int> gb = new Gen<double, int>(10.125, 2005);
Console.WriteLine(gb.t + gb.u);

To use a constraint so that you are not limited to just the base Object class:

class CompGen<T>
where T : IComparable
  public T t1;
  public T t2;

  public CompGen(T _t1, T _t2)
    t1 = _t1;
    t2 = _t2;

  public T Max()
    if (t2.CompareTo(t1) < 0)
      return t1;
      return t2;

Besides an interface, you can also use a base class, a constructor or a reference or value type for your constraints.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s