Skip to content

Instantly share code, notes, and snippets.

@mikegoatly
Last active March 8, 2021 12:05
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 mikegoatly/ae57f45f9c9325c7e477c139d84110cf to your computer and use it in GitHub Desktop.
Save mikegoatly/ae57f45f9c9325c7e477c139d84110cf to your computer and use it in GitHub Desktop.
A simple struct that automatically replaces unsupported characters from an Azure Table partition or row key value.
/// <summary>
/// A helper class that removes any characters that are unsupported in an Azure Table partition or row key value.
/// </summary>
/// <example>
/// this.PartitionKey = new SafeTableKey("Somestring with unsupported characters");
/// this.RowKey = new SafeTableKey("....");
/// </example>
public struct SafeTableKey : IEquatable<SafeTableKey>
{
private static readonly ISet<char> reservedCharacters = new HashSet<char> { '\\', '/', '#', '?', '%' };
public SafeTableKey(string key)
{
var builder = new StringBuilder(key);
for (var i = 0; i < builder.Length; i++)
{
if (reservedCharacters.Contains(builder[i]))
{
builder[i] = '_';
}
}
this.Key = builder.ToString();
}
public string Key { get; }
public override bool Equals(object? obj)
{
return obj is SafeTableKey key &&
this.Equals(key);
}
public override int GetHashCode()
{
return HashCode.Combine(this.Key);
}
public static implicit operator string(SafeTableKey key)
{
return key.Key;
}
public bool Equals(SafeTableKey other)
{
return this.Key == other.Key;
}
public static bool operator ==(SafeTableKey left, SafeTableKey right)
{
return left.Equals(right);
}
public static bool operator !=(SafeTableKey left, SafeTableKey right)
{
return !(left == right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment