0

I have a class that creates a list of numbers that count down from 100 to 0 (decremented by random values).

My aim is to apply this method to an instance of a class (where the list is one of the parameters). However, I don't believe it's working as expected and I also don't believe it's the most effective way of doing this. I'm fairly new to c#/coding so any advice would be great! Here is my code:

public class Emotion
{
    readonly string name;
    readonly List<int> statusChange;
    public Emotion(string name, List<int> statusChange)
    {
        this.name = name;
        this.statusChange = statusChange;
    }

    static void Main(string[] args)
    {
        numberGenerator();
        Emotion Hunger = new Emotion("Hunger", numberGenerator());
        
    }

    static List<int> numberGenerator()
    {
        List<int> numberGen = new List<int>();
        numberGen.Add(100);
        Random r = new Random();


        while (numberGen.Last() != 0)
        {
            int lastInt = numberGen.Last();
            int rInt = r.Next(1, 15); //might change the range 
            int newValue = lastInt - rInt;
            numberGen.Add(newValue);
        }

        //prints out list as a string
        Console.WriteLine(String.Join(",", numberGen));

        return numberGen;
    }
}

(I'm aware that some c# conventions may also be wrong in my code! I will fix it after I resolve this issue)

  • As a side note, your number generator is likely going to generate duplicates if you ever have it in a tight loop since you're creating a new `Random` inside the method. Have the random as a private field on the class instead. – Parrish Husband Jun 20 '20 at 17:49
  • 3
    You need to create a [delegate](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/using-delegates) for this. – H.G. Sandhagen Jun 20 '20 at 17:58
  • How do you know your last integer will hit zero exactly? Seems like it could skip zero and go into negative territory, resulting in an infinite loop. – John Wu Jun 20 '20 at 19:12
  • @JohnWu only until reaching `int.MinValue` :P .. but yeah you should do something like `int newValue = Mathf.Max(lastInt - rInt, 0);` – derHugo Jun 21 '20 at 01:08

1 Answers1

0

In order to accomplish the result you want, you will need to learn about Delegates

Delegates is the way to send methods in C#. Read about them in the documentation: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/

Eric Qvarnström
  • 779
  • 6
  • 21