Home > Mobile >  C# Set values of objects within an array
C# Set values of objects within an array

Time:06-07

I'm a beginner and I have a problem if the scale value is null I need to set default values of the levels that are inside the array equal to the json I have as an example,i tried to set the default values in DefaultValues but I don't know how to do the other levels.

CodePudding user response:

ScalePreferences is a List; but in your assignment you treat is a single LevelsHelper object. Assigning a List looks like this:

ScalePreferences item = new()
{
    new() { Level = 1, From = 0, To = 7},
    new() { Level = 2, From = 8, To = 15},
    ...
};

CodePudding user response:

Firstly if you always set all values for LevelsHelper you should use the constructor. Also name From and To are no are precise. And I don't understand what it mean when read code. You should refactor them

public class LevelsHelper
{
   public int Level { get; set; }
   public int From { get; set; }
   public int To { get; set; }

   public LevelsHelper(int level, int from, int to)
   {
       Level = level;
       From = from;
       To = to;
   }
}

if ScalePreferences have only List you don't need to create this object just use this List in LevelDefinition. If you have this levels in json you should read this json, not write this levels manualy

public class LevelDefinition : Base
{
     public List<LevelsHelper> Levels { get; set; }

     public override void DefaultValues()
     {
          using (StreamReader r = new StreamReader("path to json file"))
         {
             string json = r.ReadToEnd();
             Levels = JsonConvert.DeserializeObject<List<LevelsHelper>>(json);
         }
     }
}

if you don't want read it from json you can do it in this way now:

public class LevelDefinition : Base
{
     public List<LevelsHelper> Levels { get; set; }

     public LevelDefinition()
     {
         Levels = new List<LevelsHelper>();
     }

     public override void DefaultValues()
     {
          Levels.Add(new LevelsHelper(1,0,7));
          Levels.Add(new LevelsHelper(2,8,9));
          ...
     }
}
  • Related