Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Random string generator, based on format
void Main()
Random rnd = new Random();
public static class RandomExtensions
public static string GetString(this Random random, string format)
// Based on
// Added logic to specify the format of the random string (# will be random string, 0 will be random numeric, other characters remain)
StringBuilder result = new StringBuilder();
for(int formatIndex = 0; formatIndex < format.Length ; formatIndex++)
case '0': result.Append(getRandomNumeric(random)); break;
case '#': result.Append(getRandomCharacter(random)); break;
default : result.Append(format[formatIndex]); break;
return result.ToString();
private static char getRandomCharacter(Random random)
return chars[random.Next(chars.Length)];
private static char getRandomNumeric(Random random)
string nums = "0123456789";
return nums[random.Next(nums.Length)];

This comment has been minimized.

Copy link
Owner Author

@SamVanhoutte SamVanhoutte commented Jan 22, 2015

This extension method (on Random) allows to generate a random string, in the format of your choice. This was added as a solution on StackOverflow:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.