NoChance
NoChance

Reputation: 5752

Object initialization does not respect passed property value

The code below was written for testing only, it mixes auto property setting with "palin old method" of property setting.

I noticed that that creating the instance p1 did not properly set the value for the Status property when the initialization was invoked (it shows as zero). However, as expected, setting the property outside the intialization statement works correctly.

My quesiton is why did the statement below failed to set the Status property?

Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS);

The complete code is:

public class Program {
 public static void Main()
 {
     Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS);
     Console.WriteLine("Id={0}, Name={1}, Status={2}",p1.Id,p1.Name,p1.Status);
     //from the above, here the status=0    -----(A)
     p1.Status=Person.ACTIVE_STATUS;
     //here status is = 1111                -----(B)
     Console.WriteLine(p1.Status); 
 }
public class Person {
 public const int ACTIVE_STATUS = 111;
 public const int INACTIVE_STATUS = -2;
 private string _id;
 private string _name;

 public Person(String Id, String Name, int Status) 
 {
  this._id = Id;
  this._name = Name;
 }
 public string Id        {get {return this._id;}} 
 public string Name      {get {return this._name;} set {_name=value;} }
 public int Status       {get; set;} //Auto property
}
}

Upvotes: 0

Views: 47

Answers (2)

sommmen
sommmen

Reputation: 7618

Thats because you dont do anything with that argument specified in the constructor:

 public Person(String Id, String Name, int Status) 
 {
  this._id = Id;
  this._name = Name;
 }

Change that to:

 public Person(String Id, String Name, int status) 
 {
  this._id = Id;
  this._name = Name;
  Status = status;
 }

instead of passing a value to the constructor you can also direcrtly assign a property with a public setter e.g.:

Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS);
p1.Status = Person.ACTIVE_STATUS;

or you can use the object initializer:

Person p1 = new Person("71" ,"Sue", Person.ACTIVE_STATUS)
{
   Status = Person.ACTIVE_STATUS
};

Upvotes: 2

Sandris B
Sandris B

Reputation: 133

public Person(String Id, String Name, int Status)
    {
        this._id = Id;
        this._name = Name;
        this.Status = Status;
    }

Upvotes: 2

Related Questions