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

Wollie
  • 1
  • 1
  • What you mean by "using parameterless constructor"? – Emre Savcı Dec 12 '18 at 12:42
  • Use `Random` class – Rahul Dec 12 '18 at 12:42
  • Please add more details to your question including the code you have tried – preciousbetine Dec 12 '18 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 Dec 12 '18 at 12:43
  • parameterless constructor: class apple { int weight; public apple() { weight = ....; } } – Wollie Dec 12 '18 at 12:43
  • I know how to use the random class, but I do not want to create a Random object in every constructor, since it will not correctly use the provided random sequence. – Wollie Dec 12 '18 at 12:47
  • I would advice against using the paremeterless constructor for random initialization. This will make it hard to test, bug condition could be hard to duplicate. you might want to make sure that the random numbers you use follow a given distribution. This can only be archived if they all pull numbers from a common source. That would be hidden dependency in the class, it cannot be replaced when you want a different distributions, and prevents you from reusing the random number generator for other things. If you create a new Random instance for every Apple, each one would be seeded differently. – Theraot Dec 12 '18 at 12:48
  • 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. – Theraot Dec 12 '18 at 12:51
  • @Wollie Get the random instance from a static is an option. – Mark Baijens Dec 12 '18 at 12:52
  • I think this is what you can do: public class Apple { public Apple() { Weight = GenerateRandomWeight(); } public string Weight; public string GenerateRandomWeight() { var rnd = new Random(); var month = rnd.Next(80, 121); return month + "g"; } } – GoldenAge Dec 12 '18 at 12:53

1 Answers1

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);
        }
    }
Erik Šťastný
  • 1,487
  • 1
  • 15
  • 41