Class ObjectExtensions
Helper methods for working with any object in .NET.
Inheritance
ObjectExtensions
Assembly: Recore.dll
Syntax
public static class ObjectExtensions
Methods
|
Improve this Doc
View Source
Apply<T>(T, Action<T>)
Invokes an action on an object and passes the object through.
Declaration
public static T Apply<T>(this T obj, Action<T> action)
Parameters
Type |
Name |
Description |
T |
obj |
|
Action<T> |
action |
|
Returns
Type Parameters
|
Improve this Doc
View Source
Apply<T, TResult>(T, Func<T, TResult>)
Invokes a function on an object.
Declaration
public static TResult Apply<T, TResult>(this T obj, Func<T, TResult> func)
Parameters
Type |
Name |
Description |
T |
obj |
|
Func<T, TResult> |
func |
|
Returns
Type Parameters
Name |
Description |
T |
|
TResult |
|
Examples
This method is useful for calling a function with postfix syntax:
var syncClient = new ServiceCollection()
.Apply(ConfigureServices)
.Apply(x => x.BuildServiceProvider())
.Apply(x => x.GetService<SyncClient>());
It can also be used to simplify null-propagation logic
when the ?.
operator cannot be used:
// Before
var route = contentEndpoint is null ? null : $"{contentEndpoint}?path={forwardSlashPath}";
// After
var route = contentEndpoint?.Apply(x => $"{x}?path={forwardSlashPath}");
|
Improve this Doc
View Source
ApplyAsync<T>(Task<T>, AsyncAction<T>)
Awaits a task, invokes an asynchronous action on the result, and passes the awaited task through.
Declaration
public static Task<T> ApplyAsync<T>(this Task<T> task, AsyncAction<T> action)
Parameters
Returns
Type Parameters
|
Improve this Doc
View Source
ApplyAsync<T, TResult>(Task<T>, AsyncFunc<T, TResult>)
Awaits a task and invokes an asynchronous function on a task.
Declaration
public static Task<TResult> ApplyAsync<T, TResult>(this Task<T> task, AsyncFunc<T, TResult> func)
Parameters
Returns
Type |
Description |
Task<TResult> |
|
Type Parameters
Name |
Description |
T |
|
TResult |
|
|
Improve this Doc
View Source
StaticCast<T>(T)
Converts an object's type to T
at compile time.
Declaration
public static T StaticCast<T>(this T obj)
Parameters
Type |
Name |
Description |
T |
obj |
|
Returns
Type Parameters
Examples
Useful for overcoming those pesky variance issues:
Task<IEnumerable<object>> GetObjectsAsync()
{
var result = new[] { "hello" };
// error CS0029 because the static type of `result` is an array, not an `IEnumerable`
// return Task.FromResult(result);
// 👍
return Task.FromResult(result.StaticCast<IEnumerable<object>>());
}