This question already has answers here:
How do I generate a random integer in C#? (27 answers)
Closed6 years ago.
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.
- What you mean by "using parameterless constructor"?Emre Savcı– Emre Savcı2018-12-12 12:42:12 +00:00CommentedDec 12, 2018 at 12:42
- Please add more details to your question including the code you have triedPrecious Uwhubetine– Precious Uwhubetine2018-12-12 12:42:58 +00:00CommentedDec 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.John Alexiou– John Alexiou2018-12-12 12:43:29 +00:00CommentedDec 12, 2018 at 12:43
- 1You 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.Theraot– Theraot2018-12-12 12:51:52 +00:00CommentedDec 12, 2018 at 12:51
1 Answer1
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
Wollie
that's good for me, thanks! Are there perhaps alternatives?
Explore related questions
See similar questions with these tags.