Wednesday, April 30, 2014

Math.Min vs. Random.Next in C# - To be (static) or not to be?

As I carefully read through my notes, I had to stop and ask, "Why do I need to create an object for class Random? It bothered me to no end because I had just read about Math.Min being a static method. (Static methods mean you are not required to create an object prior to calling the method.) Yet here I was, perusing an example that created an object of class Random before calling the Next method.

My problem was my assumption. My assumption was that Random.Next was a static method since I had just been reading about static methods in a different section of my lesson/text. It was not explicitly pointed out that I was no longer reading about static methods and I just assumed every method discussed was static.

As a lawyer, I should have been more discerning. Luckily, the light bulb went off and I started a search for "Is Random.Next a static method in C#?" Turns out, I was not the only one who had this question. Stack Overflow turned up first in my search and someone asking the same question received enlightening answers on why Random.Next cannot be static. Although it would have been nice if someone had noted that we were no longer talking about static methods, the fact is that Random.Next was actually discussed in a section on the .NET framework class library in general, not in the section on static methods.

So, for all you noobs who were perplexed as I was, the answer is that Random.Next is not a static method. This is why you must create an object before calling the Next method. Just watch what you're reading and don't assume too much.

No comments:

Post a Comment