0

since I have the code below

public class student
{
    public enum Level
    {
        novice,
        adept,
        master
    }
    private Level _skillevel;
    public student()
    {
      _skillevel = 
      //to assign a random value from novice, adept and master
     }

what I expect is that each time a student object created, it will be assign a random skill level. How could I exeucte it? thanks for helps.

1 Answers1

2

Get a random value of enum

 public student()
    {
        Array values = Enum.GetValues(typeof(Level));
        Random random = new Random();
        Level _skillevel = (Level)values.GetValue(random.Next(values.Length));
    }

If you are planning to create the object of student in a loop then it is advisable to keep object of Random class as static.

Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35
  • 1
    @YunxiangLi If that is correct then don't forget to accept this as correct answer :) – Ranjit Singh May 21 '16 at 08:10
  • I advise you to pass in the `Random` object as a parameter and not create it inside the method. Otherwise if you call it more than once every few milliseconds, it won't be properly random. [Create a `Random` once somewhere, and pass it around.](http://stackoverflow.com/a/7251724/106159) – Matthew Watson May 21 '16 at 08:21
  • @MatthewWatson, Right the correct method would be passing the random variable in constructor, but then also I would advice to keep the Random variable as static in some static class – Ranjit Singh May 21 '16 at 08:50