dotnet
dotnet copied to clipboard
out parameter for Guard.IsAssignableToType<T>
Overview
Add a Guard.IsAssignableToType<T>
with an out parameter of out T cast
API breakdown
/// <summary>
/// Asserts that the input value can be assigned to a specified type.
/// </summary>
/// <typeparam name="T">The type to check the input value against.</typeparam>
/// <param name="value">The input <see cref="object"/> to test.</param>
/// <param name="cast">The input as a <see cref="T"/>.</param>
/// <param name="name">The name of the input parameter being tested.</param>
/// <exception cref="ArgumentException">Thrown if <paramref name="value"/> can't be assigned to type <typeparamref name="T"/>.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsAssignableToType<T>(object value, out T? cast, [CallerArgumentExpression("value")] string name = "")
{
if (value is T)
{
cast = (T)value;
return;
}
ThrowHelper.ThrowArgumentExceptionForIsAssignableToType<T>(value, name);
}
Usage example
public void Foo(IBase arg)
{
Guard.IsAssignableToType<Child>(arg, out Child child);
...
}
Breaking change?
No
Alternatives
public void Foo(IBase arg)
{
Guard.IsAssignableToType<Child>(arg);
var child = (Child)arg;
...
}
Additional context
No response
Help us help you
Yes, I'd like to be assigned to work on this item
Suggestion:
public static void IsAssignableToType<T>(object value, out T? cast, [CallerArgumentExpression("value")] string name = "")
{
- if (value is T)
+ if (value is T typed)
{
- cast = (T)value;
+ cast = typed;
return;
}
ThrowHelper.ThrowArgumentExceptionForIsAssignableToType<T>(value, name);
}