-1

I am a .net junior developer I have a c# code where I am supposed to generate the last four digits.

Sender = “PNP1.000(four auto generated random number)”

How do I go about autogenerating the 4 random numbers

And adding it to the string value

Any code will help and all answers are welcomed

1 Answers1

-3

There is a class named Random in .Net Framework that you can use for that. You will have to generate them using the method Next(Int32, Int32) in a loop, and store each result in an array.

Finally you can use string.join() to assemble or join each value of the array with a separator if needed.

Also, read this article:

https://www.tutorialsteacher.com/articles/generate-random-numbers-in-csharp

I let you remix the lines below according to your needs, so the code would be :

namespace ConsoleApp1
{
    class Program
    {
        public static void Main()
        {
            int padMaxLength = 4;
            char padChar = '0';
            
            Random rd = new Random();

            List<string> array = new List<string>(4);
            array.Add(rd.Next(1, 9999).ToString().PadLeft(padMaxLength, padChar));
            array.Add(rd.Next(1, 9999).ToString().PadLeft(padMaxLength, padChar));
            array.Add(rd.Next(1, 9999).ToString().PadLeft(padMaxLength, padChar));
            array.Add(rd.Next(1, 9999).ToString().PadLeft(padMaxLength, padChar));

            string sender = "PNP1.000 " + string.Join(".", array.ToArray());
            Console.WriteLine(sender);

            Console.ReadKey();
        }
    }
}
Rivo R.
  • 1
  • 2
  • This generates numbers from 1 to 9998, instead of 0 to 9999. String formatting would be more effective and readable. The question is not clear, the OP apparently confusing numbers and digits, so this is perhaps not strictly an answer to the actual question. – Bent Tranberg Feb 03 '22 at 02:41