c# 3.0 - Unexpected C# behaviour with autoproperties and constructors -
it took me debugging figure out (or think). let code loose on , see come with. there simple contact
class with:
- some auto-properties,
- a parameterized constructor increments
contact.id
property , sets other properties according arguments gets - a parameterless constructor calls parameterized constructor default values.
first see code; output , question follows code:
using system; class program { private static void main(string[] args) { contact[] contacts_array = { //contact 0 new contact(), //contact 1 new contact { name = "contactname1", age = 40, email = "emailaddress1@email.com" }, //contact 2 new contact { name = "contactname2", age = 41, email = "emailaddress2@email.com" }, //contact 3 new contact("contactname3", 42, "emailaddress3@email.com"), }; foreach (var contact in contacts_array) console.writeline(contact); console.readline(); } } public class contact { public static int totalcontacts = 0; public int id { get; private set; } public string name { get; set; } public int? age { get; set; } public string email { get; set; } public contact() { new contact("anonymous", null, "anonymous@unknown.com"); } public contact(string name, int? age, string email) { id = contact.totalcontacts++; name = name; age = age; email = email; } public override string tostring() { return string.format("[contact: id={0}, name={1}, age={2}, email={3}]", id, name, age, email); } }
output:
[contact: id=0, name=, age=, email=] [contact: id=0, name=contactname1, age=40, email=emailaddress1@email.com] [contact: id=0, name=contactname2, age=41, email=emailaddress2@email.com] [contact: id=3, name=contactname3, age=42, email=emailaddress3@email.com]
question:
why contact.id == 0 in second , third contacts rather being 1 , 2 respectively, despite parameterized constructor being called , increment id property?
your default constructor doesn't think does:
public contact() { new contact("anonymous", null, "anonymous@unknown.com"); }
this construct new contact
, discard it, current instance default values. here syntax you're after:
public contact() : this("anonymous", null, "anonymous@unknown.com") { }
Comments
Post a Comment