3

The problem I'm having is that Visual studio is throwing an error under the code "Random.Next(1,10);" that says:

"an object reference is required for the non-static field, method, or property 'Random.Next(int, int)' "

So, I looked at answers to other questions with similar phrases. In these examples on Stack Overflow most suggestions said that someone needed to simply make the method or class static. I tried all combinations of this in this code and it did not fix the error in Visual Studio.

Any help is appreciated, Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Data_Collector_Course_Assignment
{
    public class Device
    {
        // Returns a randoom integer between 1 and 10 as a measurement of an 
           imaginary object

        public int GetMeasurement()
        {
            int randomInt = Random.Next(1,10);
            return randomInt;
        }
    }
}
Erick Bravo
  • 33
  • 2
  • 6
  • Linked duplicate and MSDN give 2 options: "You will need to either make the property static, or *create an instance*". Since you can't change implementation of `Random` you could safely ignore all "make static" recommendations. – Alexei Levenkov Oct 28 '15 at 02:06

1 Answers1

9

it means Next is an instance method (not static). You need an instance of Random to use it:

public int GetMeasurement()
{
    Random rand = new Random();
    int randomInt = rand.Next(1,10);
    return randomInt;
}

or, shorter:

public int GetMeasurement()
{        
    int randomInt = new Random().Next(1,10);
    return randomInt;
}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112