0

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.

Ibanez1408
  • 4,550
  • 10
  • 59
  • 110

6 Answers6

2

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];
Joanvo
  • 5,677
  • 2
  • 25
  • 35
1

You could convert to string :

var x = rnd.Next(1, 4).ToString()[0]
Paulo Campez
  • 702
  • 1
  • 8
  • 24
0

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
Cid
  • 14,968
  • 4
  • 30
  • 45
0

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(@"\'#\'");
Filburt
  • 17,626
  • 12
  • 64
  • 115
0

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);
Sinatr
  • 20,892
  • 15
  • 90
  • 319
0

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;
}
Bart van der Drift
  • 1,287
  • 12
  • 30