Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method that expects an array of objects

Tags:

c#

oop

I'm learning C# and have written a console program to save an an array of high scores to a file. Although the program works, how I have got it to work is making me feel uneasy and feels more of a hack than a solution so I was looking for guidance on how I should have written it.

What I am currently doing within the Main method is:

  1. Declaring an array of highscore objects
  2. Initialising them
  3. Assigning some values to the array.

I am happy with what I have done up until now, it's the following two steps that make me uneasy

  1. I then declare another HighScore object
  2. I use this object to pass the array of highscores to the SaveHighScores method.

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace HighScore
{
    class HighScore
    {
        public string Name { get; set; }

        public int Score { get; set; }

        public void SaveHighScores(HighScore[] highScores)
        {
            string allHighScoresText = "";

            foreach (HighScore score in highScores)
            { 
                allHighScoresText += $"{score.Name},{score.Score}" + Environment.NewLine;
            }

            File.WriteAllText("C:/Temp/highscores.csv", allHighScoresText);
        }

        static void Main(string[] args)
        {
            HighScore[] highScore = new HighScore[2];

            for (int i = 0; i < highScore.Length; i++)
            {
                highScore[i] = new HighScore();
            }

            highScore[0].Name = "A";
            highScore[0].Score = 100;

            highScore[1].Name = "B";
            highScore[1].Score = 200;

            // are the following two lines correct or am I missing something?
            HighScore hs = new HighScore();

            hs.SaveHighScores(highScore);

        }
    }
}
like image 600
Ian Carpenter Avatar asked Jun 22 '26 10:06

Ian Carpenter


1 Answers

Make SaveHighScores static and you won't need an instance of HighScore to call it. (You can call it directly as HighScore.SaveHighScores())

like image 132
adv12 Avatar answered Jun 23 '26 22:06

adv12



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!