In my class there are several methods with the following signature:
public static void SomeMethod()
{
...
}
Most of these methods depend on the value of the private static field. It is necessary that the caller had any way to assign a value to this field before calling any of these static methods.
I want to have a single Random object for use by all classes in the application. How do I pass a reference to this object to use it in the static methods of another class? I have a private static field in the class with static methods and a static initializer:
public static void Init(Random random)
{
_random = random;
}
But how to make sure that the initializer was called? To do the check and throw exceptions in every method, it seems to me redundant. There may be another option.
Finally I found an acceptable solution for me:
Define public static property in the class that contains application entry point:
public static Random Rnd { get; } = new Random();
Define
private static Random _random
in other classes;Implement a static constructor for other classes that includes this code:
Type type = Assembly.GetExecutingAssembly().EntryPoint.DeclaringType; var randomTypeProperties = type.GetProperties().Where(p => p.PropertyType == typeof(Random)); foreach (var propertyInfo in randomTypeProperties) { _random = (Random)propertyInfo.GetValue(null); }
I can mark a message from @Andy as the answer, because it is after all a static constructor.
Thank you to everyone who took part in the discussion.
It's never too late to learn. Yesterday, as I read about the design patterns, I realized that the Singlton is exactly what I needed:
public sealed class RandomAsSingleton : Random
{
private static volatile RandomAsSingleton _instance;
private static readonly object _syncRoot = new object();
private RandomAsSingleton() { }
public static RandomAsSingleton Instance
{
get
{
lock (_syncRoot)
{
if (ReferenceEquals(_instance, null)) { _instance = new RandomAsSingleton(); }
return _instance;
}
}
}
}
My previous solution seems to me a little bit ugly right now.