title: c# random number generator in an array with no duplicates
body: <p>I'm currently trying to create a program that generates random numbers between 1 and 45 with no duplicates. My program works when I run it without the else statement whenever a duplicate comes up it inputs the number 0, when I use the else statement the function breaks. I want to display random numbers between 1 and 45 however the variable size must dictate the size of the array. For example random integers between 1 and 45 with an array size of 35.</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  
  namespace RandomArray
  {
  public class RandomArrayNoDuplicates
  {
      static void Main(string[] args)
      {
          int size = 45;
          int[] noDuplicateArray = new int[size];
          noDuplicateArray = InitializeArrayWithNoDuplicates(size);
          DisplayArray(noDuplicateArray);
          ExitProgram();
  
      } //end Main
      static Random rng = new Random();
  
      /// &lt;summary&gt;
      /// Creates an array with each element a unique integer
      /// between 1 and 45 inclusively.
      /// &lt;/summary&gt;
      /// &lt;param name="size"&gt; length of the returned array &lt; 45
      /// &lt;/param&gt;
      /// &lt;returns&gt;an array of length "size" and each element is
      /// a unique integer between 1 and 45 inclusive &lt;/returns&gt;
      ///
      static void ExitProgram()
      {
          Console.Write("\n\nPress any key to exit program: ");
          Console.ReadKey();
      }//end ExitProgram
  
      public static int[] InitializeArrayWithNoDuplicates(int size)
      {
      int number;
      int[] noDuplicates = new int[size];
  
          for (int i = 0; i &lt; size; i++)
          {
              number = rng.Next(1, size);
              if (!noDuplicates.Contains(number))
                  noDuplicates[i] = number;
             // else
             //     i--;
          }
          return noDuplicates;
  
      }
      static void DisplayArray(int[] noDuplicates)
      {
      foreach (int element in noDuplicates)
          {
              Console.Write("\t" + element + "\n");
          }
      }
  }
  }
  </code></pre>
  
  <p>The issue lies in this bit of code:</p>
  
  <pre><code>public static int[] InitializeArrayWithNoDuplicates(int size)
      {
      int number;
      int[] noDuplicates = new int[size];
  
          for (int i = 0; i &lt; size; i++)
          {
              number = rng.Next(1, size);
              if (!noDuplicates.Contains(number))
                  noDuplicates[i] = number;
             // else
             //     i--;
          }
          return noDuplicates;
  </code></pre>
  
  <p>but I'm unsure how to fix it. I would prefer to use the random.next function rather than using enumberable approach. Thanks</p>