I know that it is not a good practice to call a method in the constructor of a class in C# but I stuck on something strange. My problem is that when I create an object of my class I need to assign a field in my object with a random number.
for instance
class RandomNumberHandler
{
private int randomNumber;
public RandomNumberHandler()
{
this.randomNumber = GenerateRandomNumber();
}
private int GenerateRandomNumber()
{
return (new Random()).Next(3000) + 1000;
}
}
In my case I need a four digit number. I thought of generating the random number in the class where I am creating the object and passing it as a parameter to the constructor but generating a random number in the other class does not seem a very good idea either because I am trying to achieve strong cohesion for my classes. I am doing this for a “High quality code” course in my university and I am looking for the best approach. Any ideas how to do this are welcome 🙂
First off: there is nothing wrong with calling non-virtual methods in the constructor. Where did you read that there was? (Note: calling virtual methods can be a problem; it is not an automatic no-no, but you need to watch what you are doing very carefully).
As an aside, it seems wasteful to generate a new
Randominstance every timeGenerateRandomNumberis called. You can extract theRandominstance to a field to fix that:But this raises another question: if
GenerateRandomNumberis only called once in each instance’s lifetime (in the constructor), then it doesn’t make sense to create a newRandomfor each object. So the next logical step is to makerandombestatic. This means thatGenerateRandomNumbercan also becomestatic(and indeed, it has to):