vendredi 24 février 2017

C#: Initialize Random() only once in a singleton pattern

I am trying to initialize only once a random variable, let's say 'rnd'. So If from many points of my program it is called, then the random variable will not be initialized again, only first time.

So I have created a singleton but I do not know how to call only once Random().

public sealed class Randomize
{
    private static Randomize instance = null;
    private static readonly object padlock = new object();

    Randomize()
    {
    }
    public static Randomize Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Randomize();
                }
                return instance;
            }
        }
    }
}

Within this class I would like to create a private readonly random variable, 'rnd', which is initialized only once, the first time, to:

Random rnd = new Random()

Then, I would like to create a property to read its value, for example:

        public Random Rnd
        {
            get { return rnd; }
        }

I do not want to allow to change its value because it is assigned first time only, so I only want the property to be readonly (get), not set.

So from many points of my program I can do:

private readonly Random rnd;
Random rnd = Randomize.Instance.Rnd;

But each time I call it using above expression I do not want to initizalize random variable again (by doing new Random()) instead I want to always obtain the same value it was rnd variable was initialized for first time.

Any ideas on how to do it?




Aucun commentaire:

Enregistrer un commentaire