Zbynek
Zbynek

Reputation: 5955

How to acces global variable in classes using the program

I have following problem: I am writing some program, which uses random numbers a lot. I have a dice with six sides, and this dice is used by many objects in several classes. What I want, is to create one global variable DICE, which would than be used by all objects.

I.e.: I have class Player, who uses a dice, and class Item, which uses a dice, etc.

The configuration of the program is stored in XML file, and when I am reading it, I would have to pass DICE object all the way down to item, who is deep inside XML structure.

So what I would like to do, is something like:

public class Item
    {
    public string Name {get; private set;}

    public const Dice dice = GLOBAL.VARIABLE.DICE;

    public Item (string name)
        {
        this.Name = name;
        }
}

and DICE would be initialized once for the whole program.

Problem with random numbers is, that if I create several Dices in the same time, they all produce the same numbers, so creating new Dice for every object read from XML, would result into several random number generators producing the same results.

Upvotes: 0

Views: 102

Answers (1)

KSdev
KSdev

Reputation: 621

public class Dice
{
    public static int Roll()
    {
        // Your Code
    }
}

You would only need to reference it as Dice.Roll

Upvotes: 1

Related Questions