0

i had a function containing code like this:

Random x = new Random();
int key = x.Next(0x21, 0x7B);
string nxt = Convert.ToString(key.ToString("X")) + 
Convert.ToString(key.ToString("X"))
 + Convert.ToString(key.ToString("X"))
 + Convert.ToString(key.ToString("X"));

Im very new to C#, help me, thank a lot

2 Answers2

1

The first two lines pick a random integer between 33 and 122 inclusive (the 0xs in .Next() mean those numbers are expressed in hexadecimal notation).

The key.ToString("X") part takes that random integer, converts it to hexadecimal notation, and returns it as a string.

As Blindy pointed out, the Convert.ToString() is redundant and not necessary since it is converting a string to a string.

The final "nxt" variable would consist of that new hexadecimal number (as a string) repeated four times.

Here's a couple of other ways to get that string repeated four times:

string nxt = new StringBuilder().Insert(0, key.ToString("X"), 4).ToString();

string nxt = String.Concat(Enumerable.Repeat(key, 4));

string nxt = $"{key}{key}{key}{key}";
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
0

That code is choosing a random number between 0x21 and 0x7B, converting it to a string in hex and repeating it four times in nxt.

There are better ways to create a string with a single character multiple times (for example, the string constructor that accepts a character and a count), and the Convert.ToString call is useless since int.ToString already returns a string.

Blindy
  • 65,249
  • 10
  • 91
  • 131