-1

I am trying to have the field "weight" in a class "apple" to be filled with a random weight - let's say between 80g an 120g. I would like to use the parameterless constructor of apple. Which would be the recommended way to do this.

10
  • What you mean by "using parameterless constructor"? Commented Dec 12, 2018 at 12:42
  • Use Random class Commented Dec 12, 2018 at 12:42
  • Please add more details to your question including the code you have tried Commented Dec 12, 2018 at 12:42
  • Please show your code (but not too much of it) so we can understand what you are trying to do. Commented Dec 12, 2018 at 12:43
  • 1
    You could have an static Random object somewhere, and that would still be bad. As I said, it is a hidden dependency. No good for testing. By the way, access to it is not thread safe. Commented Dec 12, 2018 at 12:51

1 Answer 1

1

I recommend to use static Random instance and re-use it on every constructor call like this:

 class Apple
    {
        private static Random rng = new Random();
        public int weight;

        public Apple()
        {
            weight = rng.Next(80, 121);
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

that's good for me, thanks! Are there perhaps alternatives?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.