Skip to content
Gulam Ali H. edited this page Feb 24, 2026 · 1 revision

FreakyKit.Utils — Method Reference

Namespace: FreakyKit.Utils


Array

ArrayExtensions

Method Description
array.ForEach(Action<Array, int[]> action) Iterates every element of a multi-dimensional array, invoking action with the array and the current index positions. No-ops on empty arrays.

Collections

CollectionExtensions

Method Description
collection.AddRange<T, S>(params S[] values) Adds multiple values to any ICollection<T>. S must be assignable to T.
collection.RemoveRange<T, S>(params S[] values) Removes multiple values from any ICollection<T>. Only the first occurrence of each value is removed.

ListExtensions

Method Description
list.RemoveAll<T>(Predicate<T> predicate) Removes all items matching the predicate from any IList<T>. Uses the native List<T>.RemoveAll when possible. Throws NotSupportedException on arrays, ArgumentNullException if the list or predicate is null.
list.InsertWhere<T>(T obj, Func<T, bool> predicate) Inserts obj at the first position where predicate returns false. Appends to the end if the predicate is true for every element.
list.BinarySearch<T, TKey>(Func<T, TKey> keySelector, TKey key) Binary search on a sorted IList<T> using a key selector. Returns the matching item or throws InvalidOperationException if not found. TKey must implement IComparable<TKey>.

Commands

CommandExtensions

Method Description
command.ExecuteWhenAvailable(object? parameter = null) Calls Execute on an ICommand only when CanExecute returns true. Null-safe — does nothing if the command is null.

DateTime

DateTimeExtensions

Method Description
date.IsWeekDay() Returns true if the date falls on Monday–Friday.
date.IsWeekend() Returns true if the date falls on Saturday or Sunday.
date.NextWorkday() Returns the date itself if it is already a weekday, otherwise advances day-by-day until the next weekday.

Enumerable

EnumerableExtensions

Method Description
source.ToObservable<T>() Converts any IEnumerable<T> to ObservableCollection<T>.
source.WithIndex<T>() Returns IEnumerable<(T item, int index)>. Returns empty if source is null.
source.IsNullOrEmpty<T>() Returns true for null or empty sequences. Uses Count directly when the source implements ICollection<T>.
source.DistinctBy<TSource, TKey>(Func<TSource, TKey> keySelector) Returns distinct elements based on a projected key. Preserves original order (first occurrence wins).
source.ForEach<T>(Action<T> action) Executes action for each element.
source.SingleOrDefault<T>(Func<T, bool> predicate, T default) Returns the single matching item, or default if the source is null or no match is found.
source.FirstOrDefault<T>(Func<T, bool> predicate, T default) Returns the first matching item, or default if the source is null or no match is found.
source.ElementAtOrDefault<T>(int index, T default) Returns the element at index, or default if the source is null or the index is out of range.
source.EmptyIfNull<T>() Returns an empty enumerable when source is null, otherwise returns the source unchanged.
source.Append<T>(T element) Appends a single element to the end of the sequence.
source.Prepend<T>(T element) Prepends a single element to the start of the sequence.
source.Shuffle<T>() Returns the elements in a random order using Fisher-Yates. Throws ArgumentNullException if source is null.

Note: Append, Prepend, DistinctBy, SingleOrDefault, FirstOrDefault, and ElementAtOrDefault shadow identically-signed LINQ methods. Call them as static methods (EnumerableExtensions.Append(source, element)) if you need to disambiguate.


Exceptions

ExceptionExtensions

Method Description
exception.TraceException() Walks the full inner-exception chain, builds a combined message + stack trace string, and writes it to Trace.TraceError.

Numbers

NumberExtensions

Method Description
number.IsBetween<T>(T min, T max) Returns true when min ≤ number ≤ max. Works with any type implementing INumber<T> (int, double, decimal, long, etc.).

Objects

ObjectExtensions

Method Description
obj.Clone<T>() Deep-clones an object via JSON round-trip serialisation. Returns null if the object cannot be deserialised.
obj.Is<T>() Returns true if obj is an instance of T.
obj.IsNot<T>() Returns true if obj is not an instance of T.
obj.As<T>() Safe cast — returns obj as T (null on failure).
obj.ToJson<T>(JsonSerializerOptions? options = null) Serialises the object to a JSON string.
json.FromJson<T>(JsonSerializerOptions? options = null) Deserialises a JSON string to T.
obj.XmlSerialize<T>() Serialises a class to an XML string. T must have a parameterless constructor. Throws ArgumentNullException if obj is null.
xml.XmlDeserialize<T>() Deserialises an XML string to T. Returns null on failure instead of throwing. T must have a parameterless constructor.
obj.CompareAsJson(object other) Compares two objects by their JSON representations (case-insensitive). Returns true for same reference, false if either is null or types differ.

Dependency Injection

ServiceProvider

Method Description
provider.GetService<T>() Strongly-typed wrapper around IServiceProvider.GetService(Type). Throws ArgumentNullException if provider is null. Returns null when the service is not registered.

Streams

StreamExtensions

Method Description
stream.GetMemoryStream() Copies any stream into a MemoryStream and resets its position to 0.
stream.GetBase64() Converts a stream to a Base64-encoded string. Returns null if the stream is null. Optimised for MemoryStream (calls ToArray() directly).

Strings

StringExtensions

Method Description
str.ToBase64() Encodes a UTF-8 string to a Base64 string.
str.FromBase64() Decodes a Base64 string to UTF-8. Automatically pads with = if needed.
str.RemoveUnwantedCharacters(string regex) Removes all characters matching the supplied regex pattern.
str.RemoveSpecialCharacters() Strips everything except 0-9 a-z A-Z - _ .
str.IsAlphaNumeric() Returns true when the string contains only a-z, A-Z, and 0-9.
value.ToCurrency(string cultureName) Formats a double as a culture-aware currency string (e.g. "en-US" → "$1,234.56").
str.Reverse() Returns the string with its characters in reverse order.
str.IsValidEmail() Returns true if the string is a valid email address (uses MailAddress internally; trims whitespace first).

Tasks

TaskExt

Method Description
task.RunConcurrently() Fires a Task without awaiting it (suppresses the compiler warning). Starts the task if its status is Created. Throws ArgumentNullException if task is null.
TaskExt.WhenAll<T>(params Task<T>[] tasks) Awaits all tasks and returns their results as IEnumerable<T>. Unlike Task.WhenAll, rethrows as AggregateException containing all faulted exceptions, not just the first.
task.WithAggregateException() Awaits a Task and ensures faulted tasks surface as AggregateException. Re-throws cancelled tasks as-is.
task.WithAggregateException<T>() Generic version of the above; returns the task result on success.
task.TimeoutAfter<TResult>(TimeSpan timeout) Awaits a Task<TResult> and throws TimeoutException if it does not complete within the given timespan.