When using the classname() call to create a new object does this not pass by the setter property in the class?

I was under the impression that when calling a new object that new object is built using the classes setters and thus we can put constraints on in the setter property to make sure the object is formated and within the boundries we want them to be.

    public class Commune{
        private string name;
        private int department;
        private string country;
        private string mayor;
        private int population;

        public Commune(string n, int d, string c, string m, int p)
        {
            name = n;
            department = d;
            country = c;
            mayor = m;
            population = p;
        }
        public string Name
        {
            get { return name; }
            set { name = value.ToUpper(); }
        }
        public int Department
        {
            get { return department; }
            set {
                if(value <= 0){
                    department = -1;
                }else{
                    department = value;    
                }    
            }
        }
        public string Country
        {
            get { return country; }
            set { country = value; }
        }
        public string Mayor
        {
            get { return mayor; }
            set { mayor = value.ToLower(); }
        }
        public int Population{
            get{ return population;}
            set {
                if(value <= 0){
                    population = -1;
                }else{
                    population = value;    
                }    
            }
        }
}

I coded my class "Commune" with certain rules for the properties, Name and Mayors should be formated to be in Upper and Lower respectively and the department number and population should be positive.

But when I declare a new object.

//string name, int department, string country, string mayor, int population
Commune test = new Commune("name", -5, "count", "may", -5);

It creates and object without any of the formating.
Is there any way around this or do I have to manually call the setter each time?

>Solution :

There are two ways to achieve your desire.

  1. Changing the constructor
  2. Call the Setter manually

Changing the constructor

public Commune(string n, int d, string c, string m, int p)
    {
        name = n.ToUpper();
        department = d;
        country = c;
        mayor = m.ToLower();
        population = p;
    }

Call the Setter manually

Commune test = new Commune();
test.Name= "Name"
test.Mayor= "Mayor"

Leave a Reply