Implict Operators, Generics, and Nullable #5972
Unanswered
TonyValenti
asked this question in
Q&A
Replies: 2 comments 3 replies
-
can't you just check if the value is null here: public static implicit operator Optional<T>(T? Value) {
return value is null ? default : new { Value = value, IsPresent = true };
} ? |
Beta Was this translation helpful? Give feedback.
2 replies
-
The way I do this is public static class Optional
{
public static Optional<T> FromNullable<T>(T? nullableValue) where T : struct
{
return nullableValue is { } value ? Optional.Some(value) : Optional.None<T>();
}
public static Optional<T> FromNullable<T>(T? nullableValue) where T : class
{
return nullableValue is { } value ? Optional.Some(value) : Optional.None<T>();
}
// Some<T>(T value) and None<T>() are also defined here
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have this code:
Which I can use like this:
I would like to be able to run a different code if a null/nullable value is used. For example:
Specifically, in that situation, I want to create an Optional with IsPresent = false instead of an Optional<long?>.
What is the right way to do this?
Beta Was this translation helpful? Give feedback.
All reactions