| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="FallbackValue.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | |
| | | 9 | | #pragma warning disable IDE0130 // Namespace does not match folder structure |
| | | 10 | | namespace MyNet.Primitives; |
| | | 11 | | #pragma warning restore IDE0130 // Namespace does not match folder structure |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Represents a value that can be obtained from a primary source, but falls back to an alternative source if the primar |
| | | 15 | | /// </summary> |
| | | 16 | | /// <param name="fallback">The fallback source function.</param> |
| | | 17 | | /// <typeparam name="T">The type of the value.</typeparam> |
| | | 18 | | public class FallbackValue<T>(Func<T?> fallback) |
| | | 19 | | { |
| | | 20 | | private bool _hasOverride; |
| | | 21 | | private T? _override; |
| | | 22 | | |
| | 12 | 23 | | public T? Value => _hasOverride ? _override : fallback.Invoke(); |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Sets an override value that takes precedence over both the primary and fallback sources. Once set, this value wi |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="value">The override value to set.</param> |
| | | 29 | | public void SetOverride(T value) |
| | | 30 | | { |
| | 6 | 31 | | _override = value; |
| | 6 | 32 | | _hasOverride = true; |
| | 6 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Resets the override value, allowing the primary and fallback sources to determine the value again. After calling |
| | | 37 | | /// </summary> |
| | | 38 | | public void ResetOverride() |
| | | 39 | | { |
| | 3 | 40 | | _override = default; |
| | 3 | 41 | | _hasOverride = false; |
| | 3 | 42 | | } |
| | | 43 | | } |
| | | 44 | | |