Skip to content

Instantly share code, notes, and snippets.

@davecdempsey
Forked from lordlycastle/KeyValueContainer.cs
Created November 4, 2022 00:47
Show Gist options
  • Save davecdempsey/4ae54dc541ce54217e16746b87619b7c to your computer and use it in GitHub Desktop.
Save davecdempsey/4ae54dc541ce54217e16746b87619b7c to your computer and use it in GitHub Desktop.
A container class that wraps around `KeyValuePair` to make it "mutable". Also Unity inspector friendly.
/// <summary>
/// A container class which encapsulates the KeyValuePair so it shows up in the editor.
/// Also allows us to update key and value without much hassle.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
[Serializable]
public class KeyValuePairContainer<TKey, TValue>
{
/// <summary>
/// Actual KeyValuePair struct.
/// </summary>
private KeyValuePair<TKey, TValue> _keyValuePair;
/// <summary>
/// Property to allow access to _keyValuePair
/// </summary>
public KeyValuePair<TKey, TValue> KeyValuePair
{
get => _keyValuePair;
set => _keyValuePair = value;
}
/// <summary>
/// Key of the _keyValuePair.
/// When setting new value it has to create new KeyValuePair and copy over data as we cannot change it directly
/// </summary>
[ShowInInspector]
// [HorizontalGroup("KeyValue", LabelWidth = 50)]
public TKey Key
{
get => KeyValuePair.Key;
set
{
var newKeyValuePair = new KeyValuePair<TKey, TValue>(value, this.Value);
KeyValuePair = newKeyValuePair;
}
}
/// <summary>
/// Value of the _keyValuePair.
/// When setting new value it has to create new KeyValuePair and copy over data as we cannot change it directly
/// </summary>
[ShowInInspector]
// [HorizontalGroup("KeyValue", LabelWidth = 50)]
public TValue Value
{
get => KeyValuePair.Value;
set
{
var newKeyValuePair = new KeyValuePair<TKey, TValue>(this.Key, value);
KeyValuePair = newKeyValuePair;
}
}
#region Constructors
/// <summary>
/// Convenience constructor that takes KeyValuePair object.
/// </summary>
/// <param name="keyValuePair"></param>
public KeyValuePairContainer(KeyValuePair<TKey, TValue> keyValuePair)
{
this.KeyValuePair = keyValuePair;
}
/// <summary>
/// Convenience constructor that takes key and value arguments.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public KeyValuePairContainer(TKey key, TValue value)
{
KeyValuePair = new KeyValuePair<TKey, TValue>(key, value);
}
/// <summary>
/// Default constructor.
/// </summary>
public KeyValuePairContainer()
{
KeyValuePair = new KeyValuePair<TKey, TValue>();
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment