C
C#9mo ago
Emelie

❔ I don´t understand this line of code at all (random char letter)

Hi, I am finding it really hard to understand how its possible to randomize a letter like this: Random rnd = new Random(); char randomChar = (char)rnd.Next('a', 'z'); I thought that the Next() method only could take int's as a parameter?
12 Replies
Angius
Angius9mo ago
Chars have an implicit conversion to int Because that's basically what they are The character's location on the ASCII table
Emelie
Emelie9mo ago
doesn´t the (char) make it an explicit conversion?
Angius
Angius9mo ago
Yes, the resulting int is the explicitly converted char->int is implicit int->char is explicit
Emelie
Emelie9mo ago
so just to be clear, char randomChar = (char)rnd.Next('a', 'z'); is an explicit conversion, and a and z already are represented by numbers in the ASCII table?
Angius
Angius9mo ago
The bit about the ASCII table is why chars are basically ints 'a' and 'z' can be used in place of itegers because an implicit conversion exists
MODiX
MODiX9mo ago
Angius
REPL Result: Success
int x = 'a';
int x = 'a';
Compile: 421.767ms | Execution: 27.313ms | React with ❌ to remove this embed.
MODiX
MODiX9mo ago
Angius
REPL Result: Failure
char x = 56;
char x = 56;
Exception: CompilationErrorException
- Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?)
- Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?)
Compile: 476.993ms | Execution: 0.000ms | React with ❌ to remove this embed.
Angius
Angius9mo ago
As you can see Implcit conversion works one way but not the other
Emelie
Emelie9mo ago
so the (char) conversion is to make sure that the variable randomChar is converted? while the 'a' and 'z' parameters are not necessary to convert?
Angius
Angius9mo ago
Basically
Emelie
Emelie9mo ago
ok, thanks!
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.