Skip to content

Commit 2f8b6ab

Browse files
authored
1 parent d6df2f3 commit 2f8b6ab

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using System.Collections.Generic;
2+
3+
/// <summary>
4+
/// A simple static class to get and set globally accessible variables through a key-value approach.
5+
/// </summary>
6+
/// <remarks>
7+
/// <para>Uses a key-value approach (dictionary) for storing and modifying variables.</para>
8+
/// <para>It also uses a lock to ensure consistency between the threads.</para>
9+
/// </remarks>
10+
public static class GlobalVariables
11+
{
12+
13+
private static readonly object lockObject = new object();
14+
private static Dictionary<string, object> variablesDictionary = new Dictionary<string, object>();
15+
16+
/// <summary>
17+
/// The underlying key-value storage (dictionary).
18+
/// </summary>
19+
/// <value>Gets the underlying variables dictionary</value>
20+
public static Dictionary<string, object> VariablesDictionary => variablesDictionary;
21+
22+
/// <summary>
23+
/// Retrieves all global variables.
24+
/// </summary>
25+
/// <returns>The global variables dictionary object.</returns>
26+
public static Dictionary<string, object> GetAll()
27+
{
28+
return variablesDictionary;
29+
}
30+
31+
/// <summary>
32+
/// Gets a variable and casts it to the provided type argument.
33+
/// </summary>
34+
/// <typeparam name="T">The type of the variable</typeparam>
35+
/// <param name="key">The variable key</param>
36+
/// <returns>The casted variable value</returns>
37+
public static T Get<T>(string key)
38+
{
39+
if (variablesDictionary == null || !variablesDictionary.ContainsKey(key))
40+
{
41+
return default(T);
42+
}
43+
44+
return (T)variablesDictionary[key];
45+
}
46+
47+
/// <summary>
48+
/// Sets the variable, the existing value gets overridden.
49+
/// </summary>
50+
/// <remarks>It uses a lock under the hood to ensure consistensy between threads</remarks>
51+
/// <param name="key">The variable name/key</param>
52+
/// <param name="value">The variable value</param>
53+
public static void Set(string key, string value)
54+
{
55+
lock (lockObject)
56+
{
57+
if (variablesDictionary == null)
58+
{
59+
variablesDictionary = new Dictionary<string, object>();
60+
}
61+
variablesDictionary[key] = value;
62+
}
63+
}
64+
65+
}

0 commit comments

Comments
 (0)