Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "an object reference is required for the non-static field, method, or property 'Random.Next(int, int)' mean? [duplicate]

Tags:

c#

random

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;
        }
    }
}
like image 207
Erick Bravo Avatar asked Oct 25 '25 03:10

Erick Bravo


1 Answers

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;
}
like image 60
Jonesopolis Avatar answered Oct 27 '25 19:10

Jonesopolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!