c# - Calling a method that expects an array of objects -
i'm learning c# , have written console program save an array of high scores file. although program works, how have got work making me feel uneasy , feels more of hack solution looking guidance on how should have written it.
what doing within main method is:
- declaring array of highscore objects
- initialising them
- assigning values array.
i happy have done until now, it's following 2 steps make me uneasy
- i declare highscore object
- i use object pass array of highscores savehighscores method.
here 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]; (int = 0; < highscore.length; i++) { highscore[i] = new highscore(); } highscore[0].name = "a"; highscore[0].score = 100; highscore[1].name = "b"; highscore[1].score = 200; // following 2 lines correct or missing something? highscore hs = new highscore(); hs.savehighscores(highscore); } } }
make savehighscores static , won't need instance of highscore call it. (you can call directly highscore.savehighscores())
Comments
Post a Comment