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
-
Array
| Boolean
| Char |
Comparison
|
Console
|
DateTime
|
Double
| EventHandler | Exception
|
Func |
IComparable |
IDisposable
|
Int32
| Math | Object
| Random | String
|
TimeSpan
-
System.Collections.Generic
-
ICollection
| IComparer |
IDictionary
| IEnumerable |
IList |
ISet |
KeyValuePair | List
| Queue
| Stack
-
System.IO
-
Path
| StreamReader | StreamWriter
-
System.Linq
-
Enumerable
-
System.Text
-
StringBuilder
-
System.Text.Json
-
System.Text.RegularExpressions
System.Threading
Interlocked
| Monitor | Thread
| ThreadStart
== 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 :
IComparable<Boolean>
- static
bool
Parse(string
s);
-
Parse a boolean from a string.
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
-
a negative value if x is less than y
-
0 if x equals y
-
a positive value if x is greater than y
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:
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. -
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 :
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.
Func
- delegate
U Func<T, U>(T arg);
-
A delegate type for a function from a type T to a type U.
IComparable<T>
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 is less than
other
0 if this
object equals other
a positive
value if this object is greater than
other
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 :
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.
Int64
: IComparable<Int64>
A long
is a signed
64-bit integer.
- static
long
Parse(string
s);
-
Parse a
long
from a string. Throws a
FormatException
if the string does not
contain a valid integer.
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
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 :
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
Replace(string
oldValue, string
newValue);
-
Return a copy of the string in which
all occurrences of
oldValue
have been
replaced with newValue
. -
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 delimiters
appear at the beginning or end of the string, or if the
string is empty. For example,
"a b".Split(' ')
=> {
"a", "b" }
"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
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 object that can compare two values of type T.
int Compare (T x, T y);
-
Return 0 if the given values are equal, -1 if x is less than y, or 1
if x is greater than y.
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 (IComparer<T> comparer);
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
IComparer<T> to order the elements. The third uses a
Comparison<T> (a delegate type).
-
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 Combine (string path1, string
path2);
-
Combine two strings into a path, inserting a directory separator
character. For example,
Path.Combine("/home/joe",
"image.png")
will return "/home/joe/image.png"
on a Linux or macOS system, where the separator character is '/'. -
static string
GetExtension (string
path);
-
Return a path's extension. For
example,
Path.Get
Extension
("/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 : 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.Linq
namespace ==
Enumerable
- static
IEnumerable<int>
Range (int
start, int
count);
-
Generate an enumeration of
count
integers beginning at start
. -
static int
Sum (this
IEnumerable<int>
source);
-
A extension method that computes
the sum of an enumeration of integers.
== 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.Text.Json namespace ==
JsonDocument
A document in JSON format.
- static JsonDocument Parse (string json);
-
Parse JSON from a string into a
JsonDocument
. -
JsonElement RootElement { get; }
-
The root element of the document.
-
virtual string ToString();
-
Convert a
JsonDocument
to a string in
JSON format.
JsonElement
A JSON element.
- JsonElement this[int index] { get; }
-
Retrieve an indexed value from an element whose kind is
Array
. -
int GetInt32 ();
-
Retrieve the integer value of an element whose kind is
Number
. -
JsonElement GetProperty (string propertyName);
-
Retrieve an indexed value from an element whose kind is
Object
. -
string? GetString ();
-
Retrieve the string value of an element whose kind is
String
. -
JsonValueKind ValueKind { get; }
-
The kind of this element.
JsonSerializer
- static T? Deserialize<T> (string json,
JsonSerializerOptions? options = default);
-
Deserialize a JSON string to an object.
-
static string Serialize<T> (T value, JsonSerializerOptions?
options = default);
-
Serialize an object to a string in JSON format.
JsonSerializerOptions
Options that can be used with JsonSerializer
.
- bool IncludeFields { get; set; }
-
Indicates whether fields are serialized. The default is false (i.e.
only public properties are serialized).
JsonValueKind
An enumeration representing a kind of JSON
element. Values include Number
, False
,
True
, String
,
Array
, Object
,
Null
.
== System.Text.RegularExpressions namespace ==
This namespace contains classes that can match
regular expressions in strings. See the regular
expression syntax summary.
Group
A group that was matched.
- int Index { get; }
-
The position in the input string where the match occurred.
-
string Value { get; }
-
The string that was matched.
GroupCollection : IEnumerable<Group>
A collection of groups in a single match.
- Group this[int groupnum] { get; }
-
An indexer that returns a single group by its integer index.
Match
A Match represents a single match of a regular
expression.
- GroupCollection Groups { get; }
-
Return all groups in the match.
-
int Index { get; }
-
The position in the input string where the match occurred.
-
Match NextMatch();
-
Return a new Match object with results for the next match in the
input string.
-
bool Success { get; }
-
True if this was a successful match.
-
string Value { get; }
-
The string that was matched.
MatchCollection : IEnumerable<Match>
A collection of matches of a regular expression
pattern.
- Match this[int i] { get; }
-
An indexer that returns a single match by its integer index.
RegEx
- static bool IsMatch (string input, string
pattern);
-
Return true if the input string contains a match for the given
pattern.
-
static Match Match (string input, string pattern);
-
Return a Match object representing the first match of the given
pattern in the input string. If no matches are found, return a Match
object whose Success property is false.
-
static MatchCollection Matches (string input, string pattern);
-
Return a MatchCollection object representing all matches of the
given pattern in the input string.
-
static string Replace (string input, string pattern, string
replacement);
-
Return a copy of the input string in which all matches of the given
pattern have been replaced by the given replacement string.
==
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 and return the decremented value.
-
static int Increment (ref int location);
-
Increment an integer atomically and return the incremented value.
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();