Naty Bizz
Naty Bizz

Reputation: 2342

Set default value to member class in c#

I need to set a default value to a member class, this value can vary and it's set at the beginning of the execution; I have this so far, minScore is my default value

public class Zones : GeneralIndicator
{
   public int IndicatorType { get; set; } 
   public string Code { get; set; }
   public string Score { get; set; } //TODO: calcular desde aca el score usando el indicatortype
   public double Latitude { get; set; }
   public double Longitude { get; set; }

   private int minScore = 0;

   public void setMinScore(int value)
   {
      minScore = value;
   }
}

I get the minScore value as a parameter when calling the application. What's the best way to set minScore for every object generated in runtime?

Upvotes: 3

Views: 2014

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500035

Two options:

  • Create a ZonesFactory class, which takes a defaultMinScore in the constructor (to remember) and has a CreateZones method which creates an instance and sets the min score:

    public class ZonesFactory
    {
        private readonly int defaultMinScore;
    
        public ZonesFactory(int defaultMinScore)
        {
            this.defaultMinScore = defaultMinScore;
        }
    
        public Zones CreateZones()
        {
            return new Zones(defaultMinScore);
        }
    }
    

    Note that here I'm assuming you also create a new constructor for Zones which takes the minScore as a parameter. I suggest you get rid of the setMinScore method (which violates .NET naming conventions apart from anything else).

  • Use a static variable to keep the default, and set it in the Zones constructor

Personally I'd prefer the first of these.

Upvotes: 7

Related Questions