-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
OfType for Option<T> #810
Comments
We have |
I think our main concern was to have upcasts type-checked which the Maybe this is also a documentation issue? There's currently nothing pointing you from What do you think @FreeApophis? |
|
One of the issues with Idea 2: public static class OptionExtensions
{
public static Option<TResult> UpCast<TSource, TResult>(this Option<TSource> option, TypeMarker<TResult> marker)
where TSource : TResult
where TResult : notnull;
}
public readonly struct TypeMarker<TResult>;
// Usage
Option<string> option = ...;
option.UpCast(default(TypeMarker<object>)); We could make this more natural to call by introducing a factory function for the type marker, something like Option<string> option = ...;
option.UpCast(Cast.To<object>()); This would make the cast methods a lot more discoverable than the separate classes. Idea 3: // Usage:
Option<string> option = ...;
option.Cast().Up<object>();
public static partial class OptionExtensions
{
public static OptionCastBuilder<TSource> Cast<TSource>(this Option<TSource> option)
where TSource : class
=> new(option);
}
public readonly struct OptionCastBuilder<TSource>(Option<TSource> option)
where TSource : class
{
public Option<TResult> Up<TResult>()
// where TSource : TResult
where TResult : class
=> option.Select(x => (TResult)(object)x);
public Option<TResult> Down<TResult>()
where TResult : class, TSource
=> option.SelectMany(x => Option.FromNullable(x as TResult));
} The downside here is that there's no way for us to do the |
I prefer idea 1. despite of boxing. It would be similar to IEnumerable, and the user code stays consistent. |
The
OfType
extension method would make the code more succinct, like a.Where(v => v is T).Select(v => (v as T)!)
The text was updated successfully, but these errors were encountered: