-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.

askedDec 12, 2018 at 12:40
Wollie's user avatar
10
  • What you mean by "using parameterless constructor"?CommentedDec 12, 2018 at 12:42
  • UseRandom classCommentedDec 12, 2018 at 12:42
  • Please add more details to your question including the code you have triedCommentedDec 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.CommentedDec 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.CommentedDec 12, 2018 at 12:51

1 Answer1

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);        }    }
answeredDec 12, 2018 at 12:48
Erik Šťastný's user avatar
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.