.NET 2.0: Notes on Foundation Part 2 (C#)

Explicit Conversion

The following are methods for explicit conversion: System.Convert, (type) cast operator, type.ToString, type.Parse, type.TryParse, and type.TryParseExact.

 

Conversion in Custom Types

The following are ways to provide conversion for your own types: conversion operators (which are new to .NET 2.0), ToString and Parse overrides, System.IConvertible implementation, and TypeConverter class implementation.

 

File System Classes

There are 2 types of these classes: informational and utility.  Informational classes are FileInfo and DirectoryInfo, both derived from FileSystemInfoDriveInfo is also an informational class but not derived from FileSystemInfo.  Utility classes are File, Directory, and Path (which is  a useful class for parsing file system paths).

There is also this FileSystemWatcher class which provides methods for monitoring file system directories for changes.

 

Reading and Writing Files

The Stream class is an abstract class from which the following classes are derived from: FileStream, MemoryStream, CryptoStream, NetworkStream, and GZipStream.

To start a read or write operation on a file stream, you begin with the File class.  It can return a FileStream, StreamReader, or StreamWriter object.

// returns a FileStream object
FileStream readFile = File.Open(@"C:\boot.ini", FileMode.Open, FileAccess.Read);
FileStream writeFile = File.Create(@"c:\myfile.txt");

// returns a StreamReader object
StreamReader reader = File.OpenText(@"C:\boot.ini");

// returns a StreamWriter object
StreamWriter writer = File.CreateText(@"c:\myfile.txt");

// reads the entire file
Console.WriteLine(File.ReadAllText(@"C:\boot.ini"));

// writes string to new file
File.WriteAllText(@"c:\myfile.txt", "Hello World!!!");

Do not confuse the File class with the FileInfo class.  The FileInfo class does not have the capability to work with file streams.  Directory class is also provided just like there is a DirectoryInfo class.

 

Reader and Writers

The StreamReader and StreamWriter classes are derived from TextReader and TextWriter abstract classes, respectively.  All text-based readers and writers are all derived from these abstract classes.  One example is the StringReader and StringWriter pair.  There is also a reader and writer pair for reading and writing binary data, the BinaryReader and BinaryWriter.

 

MemoryStream and BufferedStream

MemoryStream class is commonly used to temporarily store data in memory before storing it to a more permanent area, such as a file.

// Create an instance of MemoryStream
MemoryStream memStrm = new MemoryStream();

// Use StreamWriter to write to the MemoryStream
StreamWriter writer = new StreamWriter(memStrm);
writer.WriteLine("Hello");
writer.WriteLine("World!!!");

// Force the writer to push the data into the underlying stream
writer.Flush();

// Create a file stream
FileStream fileStrm = File.Create(@"c:\myfile.txt");

// Write the entire Memory stream to the file
memStrm.WriteTo(fileStrm);

// Clean up
writer.Close();
fileStrm.Close();
memStrm.Close();

BufferedStream class is used to buffer reads and writes through the stream that it wraps.  The code example above for MemoryStream can be rewritten to use the BufferedStream.

FileStream fileStrm = File.Create(@"c:\myfile.txt");
BufferedStream bufferedStrm = new BufferedStream(fileStrm);
StreamWriter writer = new StreamWriter(bufferedStrm);
writer.WriteLine("Hello World!!!");
writer.Close();

 

Compression Streams

Two classes you use for compression and decompression: GZipStream and DeflateStream.  If you plan on using the compressed file with gzip tool, then use GZipStream.  Otherwise use DeflateStream which produces slightly smaller files.

Advertisements

.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.

 

Arrays

To declare, initialize and sort an array:

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

// Call a shared/static array method.
Array.Sort(arr);

// 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.

 

Generics

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;
    else
      return t2;
  }
}

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

General: It has been a while since my last post

This past year and a half gave me new skills from my last project.  I learned Regular Expression, XSLT, XPath, Java, Eclipse, and C#

In the next few weeks or months I will be making some changes on this blog.  I will be refocusing my effort now on C# instead of VB.NET.  It would be best for me to use C# as my main language so I can easily switch between Java and also since I started with C way back. 

You see Java does not seem to be far away from C# and in my last project I was able to pick up Java relatively easy.  But I am not saying I will abandon VB.NET, its just that I would prefer using C# over VB.NET

Below are links to some cheat sheets that I found that will help me retain my knowledge in Java and VB.NET as I immerse myself in C#:

Java (J2SE 5.0) and C# Comparison

VB.NET and C# Comparison