Get Random element from an array in CSharp

Description

The following code shows how to get Random element from an array.

Example


// w  ww .  j  a v a  2s.  co m
using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      string[] malePetNames = { "A", "B", "C", "D", 
                                "E", "F", "G", "H", 
                                "I", "J" };

      int mIndex = rnd.Next(0, malePetNames.Length);
      Console.WriteLine(malePetNames[mIndex]);

   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Development »




Console
Encoding
Environment
Random