This quick reference lists useful fields and methods that we will often use in Programming II. See the official API documentation for a complete reference.
All properties and methods below are public.
System
namespace ==A general-purpose exception that is thrown when an argument is invalid.
ArgumentException ();
Construct an ArgumentException.
ArgumentException (string message);
Construct an ArgumentException with an error message.
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 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.
static void Clear ();
Clear the terminal window.
static ConsoleColor ForegroundColor { get; set; }
Get or set the foreground text color.
static System.IO.TextReader In { get; }
Return a TextReader
representing console input.
static System.IO.TextWriter Out { get; }
Return a TextWriter
representing console output.
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:
On Linux or macOS, this method will return as soon as a key is pressed – it does not wait for the user to press Enter. In this situation it will never return -1.
On Windows, this method will not return until the user has entered an entire line of input. It may return -1 if the user presses Ctrl+Z.
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.
static string ReadLine ();
Read a line from standard input. Returns null
if no more
input is available.
static void SetCursorPosition (int column, int row);
Move to a position (column, row) in the terminal window. The upper-left-most character is (0, 0).
static int WindowHeight { get; set; }
The height of the terminal window in characters.
static int WindowWidth { get; set; }
The width of the terminal window in characters.
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.
enum ConsoleColor
Values include Black
, Blue
, Cyan
,
DarkBlue
, DarkCyan
, DarkGray
,
DarkGreen
, DarkMagenta
, DarkRed
,
DarkYellow
, Gray
, Green
,
Magenta
, Red
, White
, Yellow
.
A structure containing information about a key that the user has
pressed. The Console.ReadKey()
method returns an
instance of this structure.
public char KeyChar { get; }
The character corresponding to the key that was pressed.
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.
An exception that is thrown when an integer division operation attempts to divide by zero.
DivideByZeroException ();
Construct a DivideByZeroException.
DivideByZeroException (string message);
Construct an DivideByZeroException with an error message.
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.
static void Exit (int exitCode);
Exit the program immediately, returning the given status code to the operating system.
static string NewLine { get; }
The string used to represent newlines on the host machine. On Linux or macOS this is “\n”; on Windows it is “\r\n”.
delegate void EventHandler (object sender, EventArgs e);
A delegate type used for various kinds of event handlers, e.g. in GTK.
Exception ();
Construct an Exception.
Exception (string message);
Construct an Exception with an error message.
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.
Any object implementing the IComparable<T>
interface can be compared with objects of type T.
int CompareTo (T other);
Returns
a negative value if this object precedes other
0 if this object equals other
a positive value if this follows other
An exception that is thrown on an attempt to access an array or collection element that is out of bounds.
IndexOutOfRangeException ();
Construct an IndexOutOfRangeException.
IndexOutOfRangeException (string message);
Construct a IndexOutOfRangeException with an error message.
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.
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.
static int Abs (int value); static double Abs (double value);
Return the absolute number of an integer or floating-point number.
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 π.
public 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. The algorithm uses "banker’s rounding": 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.
An exception indicating that a particular operation is unsupported.
NotSupportedException ();
Construct a NotSupportedException.
NotSupportedException (string message);
Construct a NotSupportedException with an error message.
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. For value types, this method tests structural equality:
it returns true if this object's fields are all equal to the
correponding fields in obj
.
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.
delegate bool Predicate<in T>(T obj);
A function from T to bool.
A pseudo-random number generator.
Random ();
Create a new random number generator using a seed value derived from the current time.
virtual int Next (int maxValue);
Return a random integer from 0 to (maxValue
– 1).
virtual double NextDouble ();
Return a random double in the range [0.0, 1.0).
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.
char this[int index] { get; }
Retrieve the character at the given index. The first character has index 0.
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
charactes. 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.
double TotalMilliseconds { get; }
Return the total number of milliseconds in this TimeSpan
.
A Tuple represents a pair of values.
public Tuple (T item1, U item2);
Construct a Tuple.
public T Item1 { get; }
Return the first item in the pair.
public U Item2 { get; }
Return the second item in the pair.
System.Collections.Generic
namespace ==IEnumerable<out T>
ICollection<T>
IDictionary<K, V>
Dictionary<K, V>
(hash table)
SortedDictionary<K, V>
(balanced
binary tree)
SortedList<K, V>
(sorted array)
IList<T>
List<T>
(array)
ISet<T>
HashSet<T>
(hash table)
SortedSet<T>
(balanced binary tree)
Queue<T>
(circular array)
Stack<T>
(array)
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.
int Compare (T x, T y);
Compare two objects of type T, returning
a negative value if x is less than y
zero if x equals y
a positive value if x is greater than y
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.
IEnumerator<T> GetEnumerator ();
Return an IEnumerator
that can traverse all elements in
this IEnumerable
.
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.
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.
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.
KeyNotFoundException ();
Construct a KeyNotFoundException.
KeyNotFoundException (string message);
Construct a KeyNotFoundException with an error message.
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 ();
Construct an empty List.
List (IEnumerable<T> e);
Construct a List containing elements copied from the given
IEnumerable
.
List<T> GetRange (int index, int count);
Create a shallow copy of a range of elements in a list. The range
starts at index
and has count
elements.
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.
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.
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 ==static bool Exists (string path);
Return true if the given file exists.
static string ReadAllText (string path);
Return a string containing the entire contents of the given text file.
StreamReader (string path);
Open a file for reading. The file is assumed to use the UTF-8 encoding. Throws a FileNotFoundException if the file does not exist.
StreamWriter (string path);
Open a file for writing. The file will be written in UTF-8 encoding.
StringReader (string s);
Open a string for reading.
StringWriter ();
Create a StringWriter
that can be used to build up a
string.
string ToString ();
Return a string containing all characters that have been written to
this StringWriter
.
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 Peek ();
Return the next character without actually reading it. Returns -1 at end of data.
int Read ();
Read a single character and return its character code. Returns -1 at end of data.
string ReadLine ();
Read a line. Returns null
at end of data.
void Close ();
Close a writer and release any associated resources.
void Write (char value); void Write (double value); void Write (int value); void Write (string value);
Write a string or other values.
void WriteLine (char value); void WriteLine (double value); void WriteLine (int value); void WriteLine (string value);
Write a string or other value, followed by a newline.
System.Linq
namespace ==static IEnumerable<T> Empty<T> ();
Return an empty enumeration.
static IEnumerable<int> Range (int start, int count);
Return an enumeration of count
successive integers,
beginning with start
.
Example:
foreach (int i in Enumerable.Range(2, 4)) WriteLine(i); // writes 2, 3, 4, 5
Aggregate<T>(Func<T, T, T> f);
Reduce this enumeration by repeatedly combining elements.
(Traditionally this higher-order function is called reduce
.)
Example:
int[] a = { 2, 3, 5, 7 }; int p = a.Aggregate((i, j) => i * j); // now p = 210 (= 2 * 3 * 5 * 7)
bool All<T>(Func<T,bool> cond);
Return true if the given condition is true for all elements in this collection.
Example:
int[] a = { 2, 3, 5, 7 }; bool b = a.All(i => i % 2 == 0); // now b = false
bool Any<T>(Func<T,bool> cond);
Return true if the given condition is true for any elements in this collection.
Example:
int[] a = { 2, 3, 5, 7 }; bool b = a.Any(i => i % 2 == 0); // now b = true IEnumerable<T> Concat<T>(IEnumerable<T> second);
Concatenate two enumerations.
Example:
int[] a = { 2, 4, 6 }; int[] b = { 1, 3, 5 }; int[] c = a.Concat(b).ToArray(); // { 2, 4, 6, 1, 3, 5 }
IEnumerable<T> Append<T> (T element);
Prepend an element to this enumeration.
Example:
int[] a = { 3, 5, 7 }; int[] b = a.Append(2).ToArray(); // now b = { 3, 5, 7, 2 } int Count<T>();
Return the number of elements in an enumeration.
Example:
int[] a = { 2, 4, 5, 9 }; int b = a.Count(); // now b = 4
T Max<T>();
Return the maximum value in this enumeration.
Example:
int[] a = { 7, 2, 1, 8, 4 }; int m = a.Max(); // 8
IEnumerable<T> OrderBy<T,K>(Func<T,K> keySelector);
Sort this enumeration by an arbitrary key.
Example:
string
[] a = {
"lemon"
,
"grape"
,
"pineapple"
,
"pear"
,
"fig"
};
string[]
b =
a.OrderBy(t => t.Length).ToArray();
// now b = { "fig", "pear", "lemon", "grape", "pineapple" }
IEnumerable<T> OrderByDescending<T,K>(Func<T,K> keySelector);
Sort this enumeration by an arbitrary key, in descending order.
Example:
string[] a = { "lemon", "grape", "pineapple", "pear", "fig" }; string[] b = a.OrderByDescending(t => t.Length).ToArray(); // now b = { "pineapple", "lemon", "grape", "pear", "fig" }
IEnumerable<T> Prepend<T> (T element);
Prepend an element to this enumeration.
Example:
int[] a = { 3, 5, 7 }; int[] b = a.Prepend(2).ToArray(); // now b = { 2, 3, 5, 7 }
IEnumerable<U> Select<T, U>(Func<T, U> f);
Map the given function over this enumeration. (Traditionally this
higher-order function is called map
.)
Example:
int[] a = { 2, 4, 3, 5, 7 }; int[] b = a.Select(i => i + 3).ToArray(); // { 5, 7, 6, 8, 10 }
IEnumerable<U> SelectMany<T, U>(Func<T, IEnumerable<U>> f);
Map by the given function and flatten the result (an enumeration of enumerations) into a simple enumeration.
Example:
int[] a = { 100, 200, 300 }; int[] b = a.SelectMany(i => Enumerable.Range(i, 3)).ToArray(); // now b = { 100, 101, 102, 200, 201, 202, 300, 301, 302 }
bool SequenceEqual<T>(IEnumerable<T> e);
Return true if this enumeration is identical to the enumeration e
,
i.e. it contains the same elements in the same order.
Example:
int[] a = { 1, 2, 3 }; int[] b = { 1, 2, 3 }; WriteLine(a.SequenceEqual(b)); // writes 'True'
T Sum<T>();
Return the sum of values in this enumeration.
Example:
int[] a = { 2, 4, 6, 8 }; int b = a.Sum(); // now b = 20
IEnumerable<T> Take<T>(int count);
Take elements from this enumeration until either the enumeration ends
or count
elements have been reached.
Example:
int[] a = Enumerable.Range(10, 5).Take(3).ToArray(); // now a = { 10, 11, 12 }
IEnumerable<T> TakeWhile<T>(Predicate<T> cond);
Take elements from this enumeration only for as long as the given condition is true.
Example:
int[] a = Enumerable.Range(10, 10).TakeWhile(i => i % 7 != 0).ToArray(); // now a = { 10, 11, 12, 13 }
T[] ToArray<T>();
Convert an enumeration to an array.
HashSet<T> ToHashSet<T>();
Convert an enumeration to a HashSet.
List<T> ToList<T>();
Convert an enumeration to a List.
IEnumerable<T> Where<T>(Predicate<T>
Filter this enumeration, keeping only elements where cond
is true. (Traditionally this higher-order function is called filter
.)
Example:
int[] a = Enumerable.Range(10, 10).Where(i => i % 2 == 0).ToArray(); // now a = { 10, 12, 14, 16, 18 }
System.Threading
namespace ==static void Sleep (int milliseconds);
Sleep for the given number of milliseconds.