Skip to content

Instantly share code, notes, and snippets.

@Regenhardt
Last active July 8, 2021 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Regenhardt/d9ed398f947c25f4743dde3e88a359d4 to your computer and use it in GitHub Desktop.
Save Regenhardt/d9ed398f947c25f4743dde3e88a359d4 to your computer and use it in GitHub Desktop.
Is it a dictionary? Is it a value? Yes!
public class DictWithDefault<TKey, TValue>
{
public readonly TValue DefaultValue;
private readonly Dictionary<TKey, TValue> values = new Dictionary<TKey, TValue>();
public DictWithDefault(TValue defaultValue = default)
{
this.DefaultValue = defaultValue;
}
public TValue this[TKey key]
{
get => this.values.TryGetValue(key, out var val) ? val : this.DefaultValue;
set => this.values[key] = value;
}
public static implicit operator TValue(DictWithDefault<TKey, TValue> dict) => dict.DefaultValue;
public static implicit operator DictWithDefault<TKey, TValue>(TValue art) =>
new DictWithDefault<TKey, TValue>(art);
public static bool operator ==(DictWithDefault<TKey, TValue> thisOne, TValue thatOne) =>
EqualityComparer<TValue>.Default.Equals(thatOne, thisOne != null ? thisOne.DefaultValue : default);
public static bool operator !=(DictWithDefault<TKey, TValue> thisOne, TValue thatOne) => !(thisOne == thatOne);
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) ||
obj is DictWithDefault<TKey, TValue> dict
&& Equals(this, dict);
}
protected bool Equals(DictWithDefault<TKey, TValue> other)
{
return EqualityComparer<TValue>.Default.Equals(this.DefaultValue, other.DefaultValue) && Equals(this.values, other.values);
}
public override int GetHashCode()
{
unchecked
{
return (EqualityComparer<TValue>.Default.GetHashCode(this.DefaultValue) * 397) ^ (this.values != null ? this.values.GetHashCode() : 0);
}
}
}
@mr5z
Copy link

mr5z commented Jul 8, 2021

You should press ctrl + A -> ctrl+shift+tab

@Regenhardt
Copy link
Author

Fair enough. ctrl+shift+tab didn't do anything though, so I just pressed shift+tab.

@mr5z
Copy link

mr5z commented Jul 8, 2021

Oh my bad. ctrl+shift+tab is a browser thing lol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment