Reputation: 5058
How do I convert the result of:
Random rnd = new Random();
var x = rnd.Next(1,4);
if x is 1 I just need it to be '1', if it is 2 I just need it to be '2', and if it is 3 I just need it to be '3'. Basically just add the quotation marks. Thank you.
Upvotes: 0
Views: 177
Reputation: 5817
There are several ways to do it, here are a couple of them:
Add the char zero (only works if it's one digit):
var c = (char)('0' + rnd.Next(1,4));
Convert to string and get the first character:
var c = rnd.Next(1, 4).ToString().ToCharArray()[0];
Upvotes: 2
Reputation: 1336
One more option, because we don't have enough yet:
Random rnd = new Random();
var x = rnd.Next(1,4);
char c;
switch (x)
{
case 1:
c = '1';
break;
case 2:
c = '2';
break;
case 3:
c = '3';
break;
}
Upvotes: 0
Reputation: 21999
You want to convert:
(int)1 to '1'
(int)2 to '2'
(int)3 to '3'
...
which is basically a function
char NumberToChar(int n) => (char)('0' + n);
Upvotes: 0
Reputation: 18061
If you want to create a string literal including the single quotes instead of creating an actual char as described in other answers, do this:
Random rnd = new Random();
var x = rnd.Next(1,4).ToString(@"\'#\'");
Upvotes: 0
Reputation: 702
You could convert to string :
var x = rnd.Next(1, 4).ToString()[0]
Upvotes: 1
Reputation: 15247
You can add this number to the char '0'
to get the char value.
Random rnd = new Random();
var x = rnd.Next(1,4);
char c = Convert.ToChar(x + '0');
Console.WriteLine("x : " + x + " - c : " + c); // Outputs : x : 1 - c : 1
Upvotes: 0