How to develop an extension method that may return random character(single character) from alphabet (a,b,....z).
public static char RandomLetter(this char randomchar)
{
}
How to develop an extension method that may return random character(single character) from alphabet (a,b,....z).
public static char RandomLetter(this char randomchar)
{
}
you can take advantage of byte code to char conversion, and use a simple:
random.Next(0,27) to give u the next random char (sum it with the byte value of a & convert to char).
String[] letters = {"a",.....,"z"};
Random rand = new Random();
String letter = letters[rand.Next(0,letters.Length-1)];
should do the job.
An extension method is the wrong tool here, since a random letter from the alphabet isn't related to an input letter (or am I missing something here?).
static string alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM";
static Random = new Random();
public static char RandomLetter()
{
return alphabet[random.Next(alphabet.Length)];
}
Edit (responding to comments):
You could make it into an extension method on the Random
type:
public static char NextRandomLetter(this Random random)
{
return alphabet[random.Next(alphabet.Length)];
}
(I chose not to call it NextLetterOfTheAlphabet
since it obviously should be random)
Thread-safety could be added by synchronizing on a private variable of the class that implements these method. However I think the whole locking process is more CPU taxing than pulling off a random number:
public static char SynchronizedRandomLetter()
{
lock (random) // Although the lock is not random ;)
{
return alphabet[random.Next(alphabet.Length)];
}
}
It doesn't really make sense to make it an extension method of char, as you don't use a char as input. You would rather make it just a static method.
You can make an extension method to String that picks one of the characters in the string:
public static Extensions {
public static char PickOneChar(this string chars, Random rnd) {
return chars[rnd.Next(chars.Length)];
}
public static char PickOneChar(this string chars) {
return chars.PickOneChar(new Random())
}
}
(Note the overload that takes a Random object; if you do this repeatedly you should create one Random object and pass it into the method. Creating several Random objects close in time gives you the same random sequence over and over.)
Example:
char[] pass = new char[8];
Random rnd = new Random();
for (int i = 0; i < pass.Length; i++) {
pass[i] = "23456789BCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz".PickOneChar(rnd)
}
string password = new String(pass);