If you've been given that advice, someone is probably suggesting that you declare an instance variable, but initialize it in your constructor. For example:
public class Foo
{
private readonly Random rnd;
public Foo()
{
rnd = new Random();
// Other construction code
}
}
Then you can use rnd
anywhere in your class.
This is actually mostly equivalent to:
public class Foo
{
private readonly Random rnd = new Random();
public Foo()
{
// Other construction code
}
}
... which I mostly prefer, as it shows that the initialization of rnd
has nothing to do with any constructor parameters.
As it seems that part of your difficulty is with the guessMe
variable, here's a more complete version:
public class Foo
{
private readonly Random rnd = new Random();
private int guessMe;
public Foo()
{
guessMe = rng.Next(0, 100);
}
}
This is assuming you need guessMe
to be an instance variable so you can refer to it throughout the class. On the other hand, perhaps you don't need the Random
variable to be an instance variable - if you're only generating one random number, it would be better as:
public class Foo
{
private readonly int guessMe;
public Foo()
{
Random rnd = new Random();
guessMe = rnd.Next(0, 100);
}
}
However, personally I wouldn't use either of these approaches. I would use a technique which creates a single instance of Random
per thread, to avoid both the perils of Random
being non-thread-safe, and the perils of creating two instances of Random
very close to each other in time, and ending up with the same seeds.
I've written about this reasonably extensively in an article on my site, including this class:
using System;
using System.Threading;
public static class RandomProvider
{
private static int seed = Environment.TickCount;
private static ThreadLocal<Random> randomWrapper =
new ThreadLocal<Random>(() =>
new Random(Interlocked.Increment(ref seed))
);
public static Random GetThreadRandom()
{
return randomWrapper.Value;
}
}
You can either use RandomProvider
directly (calling GetThreadRandom
every time you need to generate a random number) or you can pass RandomProvider.GetThreadRandom
into your class as a constructor argument for a parameter of type Func<Random>
- i.e. inject a dependency of "I want to be able to get an instance of Random
at any time".