|
1 | 1 | using System;
|
2 | 2 | using System.Collections.Generic;
|
| 3 | +using System.Diagnostics.CodeAnalysis; |
3 | 4 |
|
4 | 5 | namespace Hamlet
|
5 | 6 | {
|
@@ -142,6 +143,49 @@ public static U Match<T, U>(this Option<T> option, Func<T, U> some, Func<U> none
|
142 | 143 | : default(T?);
|
143 | 144 | }
|
144 | 145 |
|
| 146 | + /// <summary> |
| 147 | + /// Returns the value of an <see cref="Option{T}"/> if the option is <c>Some</c>, or <c>null</c> if it's <c>None</c>. |
| 148 | + /// </summary> |
| 149 | + /// <typeparam name="T">The type of the option's value.</typeparam> |
| 150 | + /// <param name="option">The option to get the value from.</param> |
| 151 | + /// <returns>The option's value if it's <c>Some</c>, or <c>null</c> if it's <c>None</c>.</returns> |
| 152 | + [return: MaybeNull] |
| 153 | + public static T ValueOrNull<T>(this Option<T> option) |
| 154 | + where T : class? |
| 155 | + { |
| 156 | + return option.IsSome |
| 157 | + ? option.Value |
| 158 | + : null; |
| 159 | + } |
| 160 | + |
| 161 | + /// <summary> |
| 162 | + /// Returns the value of an <see cref="Option{T}"/> if the option is <c>Some</c>, or <c>default(T)</c> if it's <c>None</c>. |
| 163 | + /// </summary> |
| 164 | + /// <typeparam name="T">The type of the option's value.</typeparam> |
| 165 | + /// <param name="option">The option to get the value from.</param> |
| 166 | + /// <returns>The option's value if it's <c>Some</c>, or <c>default(T)</c> if it's <c>None</c>.</returns> |
| 167 | + public static T ValueOrDefault<T>(this Option<T> option) |
| 168 | + where T : struct |
| 169 | + { |
| 170 | + return option.IsSome |
| 171 | + ? option.Value |
| 172 | + : default; |
| 173 | + } |
| 174 | + |
| 175 | + /// <summary> |
| 176 | + /// Returns the value of an <see cref="Option{T}"/> if the option is <c>Some</c>, or <c>defaultValue</c> if it's <c>None</c>. |
| 177 | + /// </summary> |
| 178 | + /// <typeparam name="T">The type of the option's value.</typeparam> |
| 179 | + /// <param name="option">The option to get the value from.</param> |
| 180 | + /// <param name="defaultValue">The value to return if the option is <c>None</c>.</param> |
| 181 | + /// <returns>The option's value if it's <c>Some</c>, or <c>defaultValue</c> if it's <c>None</c>.</returns> |
| 182 | + public static T ValueOr<T>(this Option<T> option, T defaultValue) |
| 183 | + { |
| 184 | + return option.IsSome |
| 185 | + ? option.Value |
| 186 | + : defaultValue; |
| 187 | + } |
| 188 | + |
145 | 189 | /// <summary>
|
146 | 190 | /// Converts a <see cref="Nullable{T}"/> to an <see cref="Option{T}"/>, based on whether the nullable has a value.
|
147 | 191 | /// </summary>
|
|
0 commit comments