2

If you use System.Random all over the place, is there a hygienic way of making sure that it's an app-wide singleton? I've though of several options, including the following:

  • Global static member -- this has the unfortunate effect of having to call SomeClass.Random.Next(). This can be mitigated with using static but the approach doesn't really scale since you have to do this everywhere.
  • Derived singleton -- simply deriving from Random (it's not sealed!) and making that class a lazy thread-safe singleton
  • Register a random in DI as a singleton and inject -- but injecting a Random into every class is really tedious

Ideally I just want to call some rand() in any class and have all of them refer to a single instance.

Dmitri Nesteruk
  • 23,067
  • 22
  • 97
  • 166
  • Multi-threading safe - https://stackoverflow.com/questions/3049467/is-c-sharp-random-number-generator-thread-safe, single-threaded - https://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number – Alexei Levenkov Feb 05 '20 at 07:20
  • @DmitriNesteruk You could just create a [custom snippet](https://learn.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019) in Visual Studio to insert something like `using static SomeNamespace.SomeClass;`, then use a shortcut of, say, "rnd" so you could just type "rnd" and press tab twice to insert it. Not ideal, but saves a lot of typing. – Matthew Watson Feb 05 '20 at 09:13

1 Answers1

3

this has the unfortunate effect of having to call SomeClass.Random.Next()

no it doesn't: consider a type like:

internal static class Foo
{
    private static readonly Random s_random = new Random();
    // todo: any thread safety concerns
    public static int Rand() => s_random.Next();
    public static int Rand(int minValue, int maxValue) => s_random.Next(minValue, maxValue);
}

Now you can add using static Declaration.Foo; at the top of a file that wants to use it, and now you can just use Rand() without anything else.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    But now imagine 50 classes using this, and having each class with a `using static` is not economical. – Dmitri Nesteruk Feb 05 '20 at 07:24
  • @DmitriNesteruk I don't buy that argument; it is no less economical than `using`, which we wouldn't care about being repeated in those same 50 files – Marc Gravell Feb 05 '20 at 07:35
  • 1
    @MarkGravell the difference is your IDE will insert a `using` for you, wheras no IDE will help you with `using static` – Dmitri Nesteruk Feb 05 '20 at 07:44