title: What happens when Object Variable in C# declared as static
body: <p>I created a <code>Random</code> class object named <code>x</code> within a <code>for</code> loop and called <code>x.next(1,7)</code> which should return a variable between <code>1</code> and <code>6</code>, both object creation and <code>x.next()</code> function is placed inside the for loop which executes <code>5</code> times instead of returning random variables it returns same value in each iteration </p>
  
  <pre><code>using System;
  
  namespace ConsoleApplication1
  {
      class Program
      {
  
          static void Main(string[] args)
          {
              for(int i=1;i&lt;=5;i++)
              {
                  Random x = new Random();
  
                  Console.WriteLine( x.Next(1,7));
              }
  
          }
      }
  }
  </code></pre>
  
  <p>My output is as follows </p>
  
  <pre><code>5
  5
  5
  5
  5
  </code></pre>
  
  <p>When i place the object declaration outside the loop it returns random variables in each iteration </p>
  
  <pre><code> using System;
  
  
          namespace ConsoleApplication1
          {
              class Program
              {
  
                  static void Main(string[] args)
                  {
                      Random x = new Random();
                      for(int i=1;i&lt;=5;i++)
                      {
  
  
                          Console.WriteLine( x.Next(1,7));
  
                      }
  
                  }
              }
          }
  </code></pre>
  
  <p>This time my output is</p>
  
  <pre><code>4
  5
  9
  3
  1
  </code></pre>
  
  <p>and also works when <code>x</code> is declared as static variable of class Program as follows</p>
  
  <pre><code>using System;
  
  
      namespace ConsoleApplication1
      {
          class Program
          {
              static Random x = new Random();
              static void Main(string[] args)
              {
  
                  for(int i=1;i&lt;=5;i++)
                  {
  
  
                      Console.WriteLine( x.Next(1,7));
  
                  }
  
              }
          }
      }
  </code></pre>
  
  <p>now output is </p>
  
  <pre><code>4
  7
  3
  7
  9
  </code></pre>
  
  <p>But i want to know why it returned same values when object is declared inside the loop
  and what happens when object variable is declared as static??</p>