JasonBock / SpackleNet

Spackle is a project that contains a number of helper methods I've used to supplement the core classes in .NET.
MIT License
14 stars 1 forks source link

Add RandomObjectGenerator Support for Single and Double Types #9

Closed JasonBock closed 8 years ago

JasonBock commented 9 years ago

Self-explanatory.

AllenConway commented 9 years ago

Here is a solution that can be used to add support for float / System.Single in Spackle. Within the RandomObjectGenerator.cs class add the following additional statement within GetHandledValue:

else if (typeof(float).IsAssignableFrom(target)) { result = new RandomObjectGeneratorResults(true, (float) this.Random.NextDouble()); }

There are several ways to generate a random float value in .NET, but this way seems to be the basic approach and it works well.

Here is a unit test to validate as well:

      `[TestMethod]
       public void GenerateForFloatArgument()
       {
           const float value = 0.58f;

           var random = new MockedRandom(value);
           var result = new RandomObjectGenerator(random).Generate<TypedArgument<float>>();
           Assert.AreEqual(value, result.Value);
       }`
JasonBock commented 9 years ago

Lots of good stuff here:

http://stackoverflow.com/questions/3365337/best-way-to-generate-a-random-float-in-c-sharp

AllenConway commented 9 years ago

Yep - I used that very link today ;) Here was the basis of my decision based on a quote from Jon Skeet:

Any reason not to use Random.NextDouble and then cast to float? That will give you a float between 0 and 1.

My thinking was that if Spackle has gone this long without float support, spending extra time writing a more involved Extension method was not something I wanted to initially invest in at this point. Especially since the other data types use straight forward random generator style approaches too.

JasonBock commented 8 years ago

Added.