Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Loops and Final Touches Static Members

setting System.Random as field

When declaring static System.Random field how I did private static readonly Random _random;

how Jeremy did private static readonly Random _random = new Random();

Question is why do you initialise a Random object using constructor? Unlike other fields that we have had so far, they just declare their object type and variable name like private MapLocation _location; private Path _path; private Turret _turret; and so on. They all did not use constructor. Do you use contructor to initialise Random object because just declaring Random obejct would contain null? Aren't we still able to use Next() or NextDouble() on _random object ?? Then does all static field need a value or be initialised? Sorry i dont understand

1 Answer

Steven Parker
Steven Parker
229,732 Points

I think you meant to ask "why do you not initialize the Random field using constructor?"

In the "Tower" class, the initialization of the "_location" variable is done in the class constructor. Since it's not static, you can be sure the constructor will run to set it up.

The "Random" variable is initialized at the same time that it is declared because it is static, which means it does not depend on the constructor and is shared among all instances.

And no, you would not be able to call methods using a null object value.