Created
November 5, 2019 12:50
-
-
Save eocron/fab4fe6a113fbc1ef15213b9e9e2f8e4 to your computer and use it in GitHub Desktop.
Random domain string generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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