Warm tip: This article is reproduced from stackoverflow.com, please click
c# properties

Random number place to property

发布于 2020-04-03 23:37:14

I am newbie in C# and I doing dice roll game with. I have problem to place random int value to property. Tried different variations but none of them working, just got more or less red wavy lines under text.

How can I place the results of that random operation into property Amount? Google does not helped me after 1,5 hour finding. Where is the problem?

using System;
using System.Collections.Generic;
using System.Text;
using static System.Random;

namespace DiceRollGame
{
    class Dice
    {
        private static Random randomnumber = new Random();

        public int Amount
        {
            get
            {
                return Amount;
            }

            set
            {
                Amount = value;
            }
        }
        public int ThrowAmount { get; set; }

        public Dice(int throwamount)
        {
            ThrowAmount = 0;
        }

        public static void Throw()
        {

            int numbervalue = randomnumber.Next(1, 6);

            Amount = int numbervalue;

        }

    }
}
Questioner
masteroscar
Viewed
60
Innat3 2020-01-31 20:45

Try this out:

class Dice
{
    private readonly Random rnd;
    public int Amount { get; set; }
    public int ThrowAmount { get; set; }
    public Dice() => rnd = new Random();
    public void Throw() => Amount = rnd.Next(1, 7); //Random() max value is exclusive
}

Usage:

Dice d = new Dice();
d.Throw();
Console.WriteLine(d.Amount);