Skip to content

Instantly share code, notes, and snippets.

@eocron
Created November 5, 2019 12:50
Show Gist options
  • Save eocron/fab4fe6a113fbc1ef15213b9e9e2f8e4 to your computer and use it in GitHub Desktop.
Save eocron/fab4fe6a113fbc1ef15213b9e9e2f8e4 to your computer and use it in GitHub Desktop.
Random domain string generator
using System;
using System.Linq;
public sealed class StringGenerator
{
private const int DefaultRandomStringLength = 10;
private static readonly Random Rnd = new Random();
private volatile char[] _charDomain;
public char[] CharacterDomain
{
get { return _charDomain; }
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length <= 0)
throw new ArgumentException("Char domain can't be empty", nameof(value));
var newDomain = value.DistinctBy(x => x).OrderBy(x => x).ToArray();
_charDomain = newDomain;
}
}
public StringGenerator()
{
CharacterDomain = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
}
public string GetString()
{
return GetString(DefaultRandomStringLength);
}
public string GetString(int count)
{
if (count <= 0)
throw new ArgumentOutOfRangeException(nameof(count));
var res = new char[count];
var domain = CharacterDomain;
// TODO: get rid off static Random (thread-local Randoms are no good too actually)
lock (Rnd)
{
for (var i = 0; i < count; i++)
{
var charIdx = Rnd.Next(domain.Length);
res[i] = domain[charIdx];
}
}
return new string(res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment