1 // 2 // Copyright (c) 2010-2023 Antmicro 3 // 4 // This file is licensed under the MIT License. 5 // Full license text is available in 'licenses/MIT.txt'. 6 // 7 using System; 8 9 namespace Antmicro.Renode.Utilities 10 { 11 /// <summary> 12 /// Wrapper class for fluent conditional actions. 13 /// </summary> 14 public class IfWrapper<T> 15 { 16 /// <summary> 17 /// The constructor. 18 /// </summary> 19 /// <param name="value">The object instance being wrapped.</param> 20 /// <param name="condition">The condition which will be used by 21 /// <see cref="Then"/> and <see cref="Else"/>.</param> IfWrapper(T value, bool condition)22 public IfWrapper(T value, bool condition) 23 { 24 this.value = value; 25 this.condition = condition; 26 } 27 28 /// <summary> 29 /// Executes the specified action on the wrapped object if the condition is true. 30 /// </summary> 31 /// <param name="action">The action to execute.</param> 32 /// <returns>The current <see cref="IfWrapper{T}"/> instance.</returns> Then(Action<T> action)33 public IfWrapper<T> Then(Action<T> action) 34 { 35 if(condition) 36 { 37 action(value); 38 } 39 return this; 40 } 41 42 /// <summary> 43 /// Executes the specified action on the wrapped object if the condition is false. 44 /// </summary> 45 /// <param name="action">The action to execute.</param> 46 /// <returns>The wrapped object.</returns> Else(Action<T> action)47 public T Else(Action<T> action) 48 { 49 if(!condition) 50 { 51 action(value); 52 } 53 return value; 54 } 55 56 /// <summary> 57 /// Ends the conditional block and returns the wrapped object. 58 /// </summary> 59 /// <returns>The wrapped object.</returns> EndIf()60 public T EndIf() 61 { 62 return value; 63 } 64 65 private readonly T value; 66 private readonly bool condition; 67 } 68 } 69