C# (.NET) Class Library Quick Reference

This quick reference lists useful classes and other types that we will often use in Programming II. See the official API documentation for a complete reference.

== Index of namespaces ==

== System namespace ==

Array

int GetLength(int dimension);
Return the length of an array in the given dimension. Dimensions are numbered starting from 0.
int Length { get; }
Return the total number of elements in an array. This is the product of the lengths of all dimensions.
Note that array elements are numbered starting with 0, so the length is not itself a valid index.
int Rank { get; }
Return the number of dimensions in an array.
static void Sort<T> (T[] array);
static void Sort<T> (T[] array, Comparison<T> comparison);
Sort an array. The first form orders elements using each element's implementation of IComparable<T>. The second form uses the specified Comparison<T> to order the elements.

Boolean = bool : IComparable<Boolean>

static bool Parse(string s);
Parse a boolean from a string.

Char = char : IComparable<Char>

A char represents a 16-bit Unicode character.

static bool IsDigit(char c);
Return true if the given character is a digit.
static bool IsLetter(char c);
Return true if the given character is an uppercase or lowercase letter.
static bool IsWhiteSpace(char c);
Return true if c is a whitespace character such as a space or newline.
static char ToLower(char c);
Convert a character to lowercase.
string ToString();
Convert a character to a string containing only that single character.
static char ToUpper (char c);
Convert a character to uppercase.

Comparison<T>

delegate int Comparison<in T>(T x, T y);
A delegate type for a method that compares two objects of the same type. The method should return

Console

static int Read();
Read a character from standard input. Returns -1 if no more input is available. If the return value is not -1, typically you will use a type cast to convert it to a char:
         int i = Read();
         if (i != -1) {
           char c = (char) i;
When standard input is coming from the terminal (i.e. is not redirected from a file), this method's behavior is platform-dependent:
static ConsoleKeyInfo ReadKey();
static ConsoleKeyInfo ReadKey(bool noEcho);
Read a key from the keyboard. This method returns as soon as the user has pressed any key.
Normally the key the user types will be echoed to the console. To suppress this echo, pass true as the value of the noEcho parameter.
Do not read input using ReadKey() when solving any ReCodEx exercise. This method always reads from the keyboard, but when your program runs on ReCodEx there is no keyboard, so the method will fail. Instead, use Read() or ReadLine() to read from standard input.
static string ReadLine();
Read a line from standard input. Returns null if no more input is available.
static void Write(char value);
static void Write(double value);
static void Write(int value);
static void Write(string value);
Write a string or other value to standard output.
static void WriteLine(char value);
static void WriteLine(double value);
static void WriteLine(int value);
static void WriteLine(string value);
Write a string or other value to standard output, followed by a newline.

DateTime

A DateTime represents an instance in time.

static DateTime Now { get; }
Return the current date/time.
static TimeSpan operator - (DateTime d1, DateTime d2);
Return the span of time between two DateTime objects.

Double = double : IComparable<Double>

A double is a 64-bit floating-point value.

const double NaN;
A special value that is not a number.
const double NegativeInfinity;
A special value that is less than any other double.
static double Parse(string s);
Parse a double from a string.
Warning: Depending on your computer's locale settings, this method might expect a string such as "3.5", or it might instead expect a string such as "3,5". To parse a string that includes a decimal point "." in any locale, call
using System.Globalization;
… 
double d = double.Parse("3.5", CultureInfo.InvariantCulture);
const double PositiveInfinity;
A special value that is greater than any other double.
string ToString();
Convert a double to a string.
Warning: Depending on your computer's locale setting, this method might produce a string such as "3.5", or it might produce "3,5". To produce a string that includes a decimal point "." in any locale, call
using System.Globalization;
… 
string s = d.ToString(CultureInfo.InvariantCulture);
If you want to limit the number of digits after the decimal point, use a format specifier:
string s = d.ToString("F2", CultureInfo.InvariantCulture);
static bool TryParse (string s, out double result);
Attempt to parse a double from a string. Returns true if successful.

EventHandler

delegate void EventHandler (object sender, EventArgs e);
A delegate type used for various kinds of event handlers, e.g. in Windows Forms.

Exception

Exception ();
Construct an Exception.
Exception (string message);
Construct an Exception with an error message.

IComparable<T>

Any object implementing the IComparable<T> interface can be compared with objects of type T.

int CompareTo (T other);
Returns

IDisposable

An object implementing IDisposable has resources that the caller should free when they are finished using the object.

void Dispose ();
Release resources associated with this object.

Int32 = int : IComparable<Int32>

An int is a signed 32-bit integer.

const int MaxValue = 2_147_483_647;
The largest value that can be stored in an int.
const int MinValue = -2_147_483_648;
The smallest value that can be stored in an int.
static int Parse(string s);
Parse an integer from a string. Throws a FormatException if the string does not contain a valid integer.
string ToString();
Convert an integer to a string.
static bool TryParse (string s, out int result);
Attempt to parse an integer from a string. Returns true if successful.

Math

static int Abs(int value);
static double Abs(double value);
Return the absolute number of an integer or floating-point number.
static double Acos(double d);
Return the arccosine in radians of the given number.
static double Asin(double d);
Return the arcsine in radians of the given number.
static double Atan2(double y, double x);
Return the arctangent in radians of the value (y / x).
static double Cos(double d);
Return the cosine of the given angle in radians.
static double Exp(double d);
Return the number e raised to the given power.
static double Log(double d);
Return the natural (base e) logarithm of a number.
static int Max(int val1, int val2);
static double Max(double val1, double val2);
Return the greater of two values.
static int Min(int val1, int val2);
static double Min(double val1, double val2);
Return the lesser of two values.
const double PI = 3.14159265358979;
The constant π.
static double Pow(double x, double y);
Return a number raised to a power.
static double Round(double a);
Round a floating-point number to the nearest integer. (Values of the form i + 0.5 (for any integer i) are always rounded towards an even number.)
static int Sign(int a);
static int Sign(double a);
Return the sign of a, which is +1, 0, or -1 in the cases where a > 0, a = 0 or a < 0, respectively.
static double Sin(double a);
Return the sine of the given angle in radians.
static double Sqrt(double d);
Return the square root of a floating-point number.
static double Truncate(double d);
Return the integer part of d, which is always smaller than (or equal to) d in absolute value.

Object = object

The Object class is the top of the class hierarchy. All types inherit directly or indirectly from Object.

virtual bool Equals (object obj);
Return true if this object is equal to obj. By default, for reference types this method tests reference equality: it returns true if this object and obj are actually the same object.
virtual int GetHashCode ();
Return a hash code for this object. If you override Equals, you must also override this method and ensure that equal values will always have the same hash code.
virtual string ToString ();
Convert this object to a string.

Random

A pseudo-random number generator.

Random();
Create a new random number generator using a seed value derived from the current time.
Random(int seed);
Create a random number generator with the given seed value.
int Next(int maxValue);
Return a random integer from 0 to (maxValue – 1).
double NextDouble();
Return a random double in the range [0.0, 1.0).

String = string : IComparable<String>

String(char[] value);
Construct a string from an array of characters.
String(char c, int count);
Construct a string that contains the character c repeated count times.
bool Contains(char c);
Return true if this string contains the character c.
int IndexOf(char c);
Return the index of the first occurrence of character c in this string, or -1 if none.
int IndexOfAny(char[] anyOf);
Return the index of the first occurrence of any of the given characters, or -1 if none.
static string Join(string separator, params string[] a);
Concatenate all the strings in a, placing the given separator string between each pair.
int Length { get; }
Return the length of a string.
string Remove(int startIndex, int count);
Return a copy of the string in which count characters starting at position startIndex have been deleted.
string[] Split(params char[] separators);
Split a string into substrings delimited by any of the given characters. If separator is null, all whitespace characters are delimiters.
Be warned that Split will return empty strings if there are repeated delimiters, or if all characters are delimiters or the string is empty. For example,

"a b".Split(' ') => { "a", "b" }

"a  b".Split(' ') => { "a", "", "b" }

" ".Split(' ') => { "", "" }

"".Split(' ') => { "" }

bool StartsWith(string prefix);
Return true if this string starts with prefix.
string Substring(int startIndex);
Return a substring containing all characters from startIndex through the end of the string.
string Substring(int startIndex, int length);
Return a substring of length characters starting at position startIndex.
char[] ToCharArray();
Convert a string to an array of characters.
string ToLower();
Convert a string to lowercase.
string ToUpper();
Convert a string to uppercase.
string Trim();
Remove all leading and trailing whitespace from a string.

TimeSpan

A TimeSpan represents a time interval.

double TotalMilliseconds { get; }
Return the total number of milliseconds in this TimeSpan.

== System.Collections.Generic namespace ==

overview

%3

ICollection<T> : IEnumerable<T>

ICollection<T> contains methods implemented by many collection classes.

void Add (T item);
Add an item to a collection.
bool Contains (T item);
Return true if the collection contains the given item.
int Count { get; }
Return the number of items in a collection.
void Clear ();
Remove all items from a collection.
bool Remove (T item);
Remove the first occurrence of the given element, if any. Returns false if the item was not present in the collection.

IDictionary<K, V> : ICollection<KeyValuePair<K, V>>

An IDictionary<K, V> is a dictionary (also known as a map or associative array).

V this[K key] { get; set; }
Get or set the item with the given key. When retrieving, throws a KeyNotFoundException if no item with the key is present.
bool ContainsKey (K key);
Return true if an item with the given key is present.
ICollection<K> Keys { get; }
Get a collection of all keys in the dictionary.
bool Remove (K key);
Remove the item with the specified key, if any. Returns true if an item was removed, false if the key was not found.
ICollection<V> Values { get; }
Get a collection of all values in the dictionary.

IEnumerable<T>

The foreach statement can iterate over any object that implements IEnumerable<T>.

IList<T> : ICollection<T>

An IList<T> is a dynamic array. See the concrete implementation List<T> below.

T this[int index] { get; set; }
Get or set the element at the given index. Will throw an exception if the index is out of bounds.
int IndexOf (T item);
Return the index of the given item, or -1 if not present.
void Insert (int index, T item);
Insert an item at a given index.
void RemoveAt (int index);
Remove the item at a given index.

ISet<T> : ICollection<T>

An ISet<T> is a dynamic set.

void IntersectWith (IEnumerable<T> other);
Modify this set to contain only elements that are also in other.
bool SetEquals (IEnumerable<T> other);
Return true if this set contains the same elements as the given collection.
void UnionWith (IEnumerable<T> other);
Modify this set to contain elements that are in the current set, in other, or in both.

KeyValuePair<K, V>

An IDictionary is a collection of KeyValuePair objects.

KeyValuePair (K key, V value);
Construct a KeyValuePair.
K Key { get; }
Get the key in a key/value pair.
V Value { get; }
Get the value in a key/value pair.

List<T> : IList<T>

A List<T> is a dynamic array. It has the methods below, and also inherits methods from IList<T> (see above).

List ();
Construct an empty List.
List (IEnumerable<T> e);
Construct a List containing elements copied from the given IEnumerable.
void Sort ();
void Sort (Comparison<T> comparison);
Sort a list's elements. The first form above uses the default comparer, which will use the elements' IComparable<T> interface if available. The second form uses the specified Comparison<T> to order the elements.
T[] ToArray ();
Convert a list to an array.

Queue<T> : IEnumerable<T>

A Queue<T> is an array-based queue.

int Count { get; }
Return the number of items in a queue.
T Dequeue ();
Remove an element from the beginning of a queue.
void Enqueue (T item);
Add an element to the end of a queue.

Stack<T> : IEnumerable<T>

A Stack<T> is an array-based stack.

int Count { get; }
Return the number of items on a stack.
T Pop ();
Pop an item from the top of a stack.
void Push (T item);
Push an item onto a stack.

== System.IO namespace ==

Path

static string GetExtension (string path);
Return a path's extension. For example, Path.GetExtension("/home/joe/image.png") returns ".png".
static string GetFileName (string path);
Return a path's filename. For example, Path.GetFileName("/home/joe/image.png") returns "image.png".
static string GetFileNameWithoutExtension (string path);
Return a path's filename without the extension. For example, Path.GetFileNameWithoutExtension("/home/joe/image.png") returns "image".

StreamReader

StreamReader(string path);
Open a file for reading. The file is assumed to use the UTF-8 encoding.
void Close();
Close a reader and release any associated resources.
bool EndOfStream { get; }
Return true if we have reached the end of the input data.
int Read();
Read a single character and return its character code. Returns -1 at end of data.
If the return value is not -1, typically you will use a type cast to convert it to a char:
         StreamReader reader = new StreamReader("input_file");

         int i = reader.Read();
         if (i != -1) {
           char c = (char) i;
string ReadLine();
Read a line. Returns null at end of data.

StreamWriter

StreamWriter(string path);
Open a file for writing. The file will be written in UTF-8 encoding.
Important: You must call the Close() method to close the file when you are done writing. If you don't do this, some or all output may not actually be written to the file!
void Close();
Close a writer and release any associated resources.
void WriteLine(string value);
Write a string, followed by a newline.

== System.Runtime.InteropServices namespace ==

Marshall

static void Copy (IntPtr source, byte[] destination, int startIndex, int length);
Copy data from unmanaged memory (i.e. memory not managed by the C#/CLR runtime) to a C# array.
static void Copy (byte[] source, int startIndex, IntPtr destination, int length);
Copy data from a C# array to unmanaged memory.

== System.Text namespace ==

StringBuilder

A StringBuilder is used for building a string incrementally. You can append a series of strings to a StringBuilder, then convert the result to a string by calling its ToString method. For large strings, this will be much faster than using string concatenation to build a string.
StringBuilder ();
Create an empty StringBuilder.
StringBuilder Append(char c);
Append a char to this StringBuilder. (The same StringBuilder is returned from the method.)
StringBuilder Append(string s);
Append a string to this StringBuilder. (The same StringBuilder is returned from the method.)
StringBuilder Clear();
Reset this StringBuilder to the empty string. (The same StringBuilder is returned from the method.)