using System; namespace EmbedIO.Sessions { /// /// Provides extension methods for types implementing . /// public static class SessionExtensions { /// Gets the value associated with the specified key. /// The desired type of the value. /// The on which this method is called. /// The key whose value to get from the session. /// /// When this method returns, the value associated with the specified key, /// if the key is found and the associated value is of type ; /// otherwise, the default value for . /// This parameter is passed uninitialized. /// /// if the key is found and the associated value is of type ; /// otherwise, . /// is . /// is . public static bool TryGetValue(this ISession @this, string key, out T value) { if (@this.TryGetValue(key, out var foundValue) && foundValue is T typedValue) { value = typedValue; return true; } #pragma warning disable CS8653 // "default" can be null - We are returning false, so value is undefined value = default; #pragma warning restore CS8653 return false; } /// Gets the value associated with the specified key. /// The desired type of the value. /// The on which this method is called. /// The key whose value to get from the session. /// The value associated with the specified key, /// if the key is found and the associated value is of type ; /// otherwise, the default value for . public static T GetValue(this ISession @this, string key) => @this.TryGetValue(key, out var value) && value is T typedValue ? typedValue : default; /// Gets the value associated with the specified key. /// The desired type of the value. /// The on which this method is called. /// The key whose value to get from the session. /// The default value to return if the key is not found /// or its associated value is not of type . /// The value associated with the specified key, /// if the key is found and the associated value is of type ; /// otherwise, . public static T GetOrDefault(this ISession @this, string key, T defaultValue) => @this.TryGetValue(key, out var value) && value is T typedValue ? typedValue : defaultValue; } }