HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Random Number Generator Class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomnumberclassgenerator

Problem

I've written an abstract class in C# for the purpose of random number generation from an array of bytes. The .NET class RNGCryptoServiceProvider can be used to generate this array of random bytes, for example.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyLibrary
{
///
/// Represents the abstract base class for a random number generator.
///
public abstract class Rng
{
///
/// Initializes a new instance of the class.
///
public Rng()
{
//
}

public Int16 GetInt16(Int16 min, Int16 max)
{
return (Int16)(min + (Int16)(GetDouble() * (max - min)));
}

public Int32 GetInt32(Int32 min, Int32 max)
{
return (Int32)(min + (Int32)(GetDouble() * (max - min)));
}

public Int64 GetInt64(Int64 min, Int64 max)
{
return (Int64)(min + (Int64)(GetDouble() * (max - min)));
}

public UInt16 GetUInt16(UInt16 min, UInt16 max)
{
return (UInt16)(min + (UInt16)(GetDouble() * (max - min)));
}

public UInt32 GetUInt32(UInt32 min, UInt32 max)
{
return (UInt32)(min + (UInt32)(GetDouble() * (max - min)));
}

public UInt64 GetUInt64(UInt64 min, UInt64 max)
{
return (UInt64)(min + (UInt64)(GetDouble() * (max - min)));
}

public Single GetSingle()
{
return (Single)GetUInt64() / UInt64.MaxValue;
}

public Double GetDouble()
{
return (Double)GetUInt64() / UInt64.MaxValue;
}

public Int16 GetInt16()
{
return BitConverter.ToInt16(GetBytes(2), 0);
}

public Int32 GetInt32()
{
return BitConverter.ToInt32(GetBytes(4), 0);
}

public Int64 GetInt64()
{
return BitConverter.ToInt64(GetBy

Solution

I think the design is pretty good. A few comments:

-
I'd rename the class to something a bit more descriptive, say RandomGenerator. Then when you implement the class you can declare it with CspGenerator: RandomGenerator or MersenneGenerator: RandomGenerator and it's obvious what the class does.

-
Comment the get() methods. IMO all public elements should be documented. Get/set could be left out, but that is a matter of preference. In particular I'd like to know what kind of range min anf max is and is used for.

-
Is getBytes() needed externally? If not, I would consider making it class-level rather than public.

The formatting is good - even in Visual Studio I've seen it get messed up as code is refactored and changed.

Context

StackExchange Code Review Q#538, answer score: 8

Revisions (0)

No revisions yet.