SoFunction
Updated on 2025-03-07

Summary of the usage of methods in C#

1. Reload

Returns a random integer.

Next() Returns a non-negative random integer.
Next(Int32) Returns a non-negative random integer smaller than the specified maximum value.
Next(Int32, Int32) Returns any integer within the specified range.

2. Next()

Returns a non-negative random integer.

1. Definition

public virtual int Next ();

return
Int32
Greater than or equal to 0 And less than  of 32 bit signed integer。

2. Example

//Next()
namespace ConsoleApp39
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            (args);

            Random rnd = new();

            ("Generating 10 random numbers:");

            for (uint i = 1; i <= 10; i++)
                ($"{(),15:N0}");
        }
    }
}

// Running results:/*
 Generating 10 random numbers:
  1,346,240,124
    723,453,914
  1,735,589,449
  1,860,966,112
  1,562,174,739
     22,804,240
    576,594,210
  1,204,251,909
  1,436,476,117
    828,029,130
 */

Generates a random number with a value ranging from 0 to less than . To generate a random number with a value ranging from 0 to some other positive number, use the (Int32) method to overload. To generate random numbers in different ranges, overload using the (Int32, Int32) method.

3. Next(Int32)

Returns a non-negative random integer smaller than the specified maximum value.

1. Definition

public virtual int Next (int maxValue);

parameter
maxValue
Int32
The upper limit of random number to generate(The upper limit value cannot be taken by random numbers)。 maxValue Must be greater than or equal to 0。

return
Int32
greater than or equal to zero and less than maxValue of 32 bit signed integer,Right now:return值of范围通常包括零但不包括 maxValue。 but,if maxValue equal 0,则return 0。

exception
ArgumentOutOfRangeException
maxValue Less than 0。

2. Example 1

// Next(Int32)
namespace ConsoleApp40
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            (args);

            (
                "This example of the () methods\n" +
                "generates the following output.\n");
            (
                "Create Random objects all with the same seed and " +
                "generate\nsequences of numbers with different " +
                "bounds. Note the effect\nthat the various " +
                "combinations of bounds have on the sequences.");

            NoBoundsRandoms(234);

            UpperBoundRandoms(234, );
            UpperBoundRandoms(234, 2000000000);
            UpperBoundRandoms(234, 200000000);

            BothBoundsRandoms(234, 0, );
            BothBoundsRandoms(234, , );
            BothBoundsRandoms(234, -2000000000, 2000000000);
            BothBoundsRandoms(234, -200000000, 200000000);
            BothBoundsRandoms(234, -2000, 2000);

            // Generate random numbers with no bounds specified.
            void NoBoundsRandoms(int seed)
            {
                (
                    "\nRandom object, seed = {0}, no bounds:", seed);
                Random randObj = new(seed);

                // Generate six random integers from 0 to .
                for (int j = 0; j < 6; j++)
                    ("{0,11} ", ());
                ();
            }

            // Generate random numbers with an upper bound specified.
            void UpperBoundRandoms(int seed, int upper)
            {
                (
                    "\nRandom object, seed = {0}, upper bound = {1}:",
                    seed, upper);
                Random randObj = new(seed);

                // Generate six random integers from 0 to the upper bound.
                for (int j = 0; j < 6; j++)
                    ("{0,11} ", (upper));
                ();
            }

            // Generate random numbers with both bounds specified.
            void BothBoundsRandoms(int seed, int lower, int upper)
            {
                (
                    "\nRandom object, seed = {0}, lower = {1}, " +
                    "upper = {2}:", seed, lower, upper);
                Random randObj = new(seed);

                // Generate six random integers from the lower to
                // upper bounds.
                for (int j = 0; j < 6; j++)
                    ("{0,11} ",
                        (lower, upper));
                ();
            }
        }
    }
}

/*
This example of the () methods
generates the following output.

Create Random objects all with the same seed and generate
sequences of numbers with different bounds. Note the effect
that the various combinations of bounds have on the sequences.

Random object, seed = 234, no bounds:
2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, upper bound = 2147483647:
2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, upper bound = 2000000000:
1947533580   954563751   662424922  1007613896  1707392518   101943116

Random object, seed = 234, upper bound = 200000000:
194753358    95456375    66242492   100761389   170739251    10194311

Random object, seed = 234, lower = 0, upper = 2147483647:
2091148258  1024955023   711273344  1081917183  1833298756   109460588

Random object, seed = 234, lower = -2147483648, upper = 2147483647:
2034812868   -97573602  -724936960    16350718  1519113864 -1928562472

Random object, seed = 234, lower = -2000000000, upper = 2000000000:
1895067160   -90872498  -675150156    15227793  1414785036 -1796113767

Random object, seed = 234, lower = -200000000, upper = 200000000:
189506716    -9087250   -67515016     1522779   141478503  -179611377

Random object, seed = 234, lower = -2000, upper = 2000:
    1895         -91        -676          15        1414       -1797
*/

3. Example 2

Generates a random integer that is used as an index to retrieve string values ​​from the array. Since the highest index of the array is less than 1 of its length, the value of the attribute is provided as the maxValue parameter.

// Next(Int32)
namespace ConsoleApp41
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Random rnd = new();
            string[] malePetNames = [ "Rufus", "Bear", "Dakota", "Fido",
                          "Vanya", "Samuel", "Koani", "Volodya",
                          "Prince", "Yiska" ];
            string[] femalePetNames = [ "Maggie", "Penny", "Saya", "Princess",
                            "Abby", "Laila", "Sadie", "Olivia",
                            "Starlight", "Talla" ];

            // Generate random indexes for pet names.
            int mIndex = ();
            int fIndex = ();

            // Display the result.
            ("Suggested pet name of the day: ");
            ("   For a male:     {0}", malePetNames[mIndex]);
            ("   For a female:   {0}", femalePetNames[fIndex]);
        }
    }
}

// Running results:/*
Suggested pet name of the day:
   For a male:     Samuel
   For a female:   Abby
*/

4. Next(Int32, Int32)

Returns any integer within the specified range.

1. Definition

public virtual int Next (int minValue, int maxValue);

parameter
minValue
Int32
The lower bound of the returned random number(The lower bound value can be taken by the random number)。

maxValue
Int32
The upper bound of the returned random number(The upper bound value cannot be taken by random number)。 maxValue Must be greater than or equal to minValue。

return
Int32
One greater than or equal to minValue And less than maxValue of 32 Signed integer,Right now:returnof值范围包括 minValue But not including maxValue。 if minValue equal maxValue,则return minValue。

exception
ArgumentOutOfRangeException
minValue Greater than maxValue。

Overload Next(Int32, Int32) returns a random integer ranging from minValue to maxValue - 1. However, if maxValue is equal to minValue, the method returns minValue. Unlike other overloads Next, which returns only non-negative values, this method can return negative random integers.

2. Example 1

Use the (Int32, Int32) method to generate random integers with three different ranges. Note that the exact output of this example depends on the seed value provided by the system passed to the constructor of the Random class.

// Next(Int32, Int32)
namespace ConsoleApp42
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            (args);

            Random rnd = new();

            ("\n20 random integers from -100 to 100:");
            for (int ctr = 1; ctr &lt;= 20; ctr++)
            {
                ("{0,6}", (-100, 101));
                if (ctr % 5 == 0) ();
            }

            ("\n20 random integers from 1000 to 10000:");
            for (int ctr = 1; ctr &lt;= 20; ctr++)
            {
                ("{0,8}", (1000, 10001));
                if (ctr % 5 == 0) ();
            }

            ("\n20 random integers from 1 to 10:");
            for (int ctr = 1; ctr &lt;= 20; ctr++)
            {
                ("{0,6}", (1, 11));
                if (ctr % 5 == 0) ();
            }
        }
    }
}

// Running results:/*
20 random integers from -100 to 100:
   -78   -13    58   -11    80
   -49    -5   -57    81   -44
    69    28   -63   -23    65
    96   -20   -37    76    18

20 random integers from 1000 to 10000:
    3738    6382    4790    2334    1875
    6557    6491    2583    2012    6601
    5929    4639    7814    3045    1737
    5512    4275    8866    2288    7201

20 random integers from 1 to 10:
     4     7     1     5     7
     2     7     6     3     4
    10     6     3     3     7
     1     3     1    10     6

 */

3. Example 2

Use the (Int32, Int32) method to generate random integers with three different ranges. Note that the exact output of this example depends on the seed value provided by the system passed to the constructor of the Random class.

// Next(Int32, Int32)
namespace ConsoleApp43
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Random rnd = new();
            string[] malePetNames = [ "Rufus", "Bear", "Dakota", "Fido",
                          "Vanya", "Samuel", "Koani", "Volodya",
                          "Prince", "Yiska" ];
            string[] femalePetNames = [ "Maggie", "Penny", "Saya", "Princess",
                            "Abby", "Laila", "Sadie", "Olivia",
                            "Starlight", "Talla" ];

            // Generate random indexes for pet names.
            int mIndex = (0, );
            int fIndex = (0, );

            // Display the result.
            ("Suggested pet name of the day: ");
            ("   For a male:     {0}", malePetNames[mIndex]);
            ("   For a female:   {0}", femalePetNames[fIndex]);
        }
    }
}

// Running results:/*
Suggested pet name of the day:
   For a male:     Samuel
   For a female:   Penny
 */

This is the end of this article about the use of methods in C#. For more related C# content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!