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.

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

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.

DateTime (int year, int month, int day);

Construct a DateTime from a year, month, and day.

int Day { get; }

Return the day; this is a number between 1 and 31.

int Hour { get; }

Return the hour; this is a number between 0 and 23.

int Minute { get; }

Return the minute; this is a number between 0 and 59.

int Month { get; }

Return the month; this is a number between 1 and 12.

static DateTime Now { get; }

Return the current date/time.

static DateTime Parse (string s);

Parse a string to produce a DateTime.

int Year { get; }

Return the year.

static DateTime operator + (DateTime d, TimeSpan t);

Add a time interval to a DateTime.

static DateTime operator - (DateTime d, TimeSpan t);

Subtract a time interval from a DateTime.

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.

const double PositiveInfinity;

A special value that is greater than any other double.

string ToString ();

Convert a double to a string.

static bool TryParse (string s, out double result);

Attempt to parse a double from a string. Returns true if successful.

Environment

static void Exit (int exitCode);

Exit the program immediately, returning the given status code to the operating system.

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.

Func

delegate U Func<in T, out U>(T arg);

A function from T to U.

delegate V Func<in T, in U, out V>(T arg1, U arg2);

A function from (T, U) to V.

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

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.

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

TimeSpan (int days, int hours, int minutes, int seconds);

Construct a TimeSpan representing the given number of days, hours, minutes, and seconds.

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.

IComparer<T>

An IComparer<T> is used to compare two objects in a custom fashion. (See the Sort() method in List<T>, below.)

int Compare (T x, T y);

Compare two objects of type T, returning

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<out T>

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

IEnumerator<T> GetEnumerator ();

Return an IEnumerator that can traverse all elements in this IEnumerable.

IEnumerator<out T>

The foreach statement uses an IEnumerator<T> to iterate over an enumerable object.

T Current { get; }

Return the current value in the enumeration. You must call MoveNext once before retrieving the first value!

void Dispose ();

Invoked when the caller has finished using this Enumerator.

bool MoveNext ();

Advance to the next value in the enumeration. Returns false if there are no more elements.

void Reset ();

Reset the enumerator to its initial position. You need not implement this method; you can simply throw a NotSupportedException.

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

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 ();

Sort a list's elements using the default comparer, which will use the elements' IComparable<T> interface if available.

void Sort (IComparer<T> comparer);

Sort a list's elements using the given IComparer<T>.

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

StreamReader : IDisposable

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 : IDisposable

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

== System.Threading namespace ==

Interlocked

This class provides atomic operations for variables that are shared by multiple threads.

static int Decrement (ref int location);

Decrement an integer atomically.

static int Increment (ref int location);

Increment an integer atomically.

Monitor

The Monitor class allows threads to acquire an exclusive lock on an object, and to wait (block) until awakened by another thread.

static void Enter (object obj);

Acquire an exclusive lock on an object.

static void Exit (object obj);

Release an exclusive lock on an object.

static void Pulse (object obj);

Wake up a single thread that is waiting on an object.

static void PulseAll (object obj);

Wake up all threads that are waiting on an object.

static bool Wait (object obj);

Release the lock on an object and block until awakened.

Thread

Thread (ThreadStart start);

Create a thread that will run the given function. The thread will not begin running until you call the Start() method.

void Join ();

Wait until a thread finishes running.

static void Sleep (int milliseconds);

Sleep for the given number of milliseconds.

void Start ();

Start running a thread.

ThreadStart

delegate void ThreadStart();