Reputation: 2269
I cannot figure out how to use the shorthand syntax without having variables that don't match or completely different names.
There is ambiguity between fields and properties, but if I name them differently I can't use the shorthand get; set; syntax. How do I fix this?
/// <summary>
/// A customer object
/// </summary>
public class Customer
{
// These are fields
private string name;
private string address;
private string city;
private string province;
private string postalCode;
private string phoneNumber;
private string emailAddress;
// These are properties
public string name { get; set; }
public string address { get; set; }
public string city { get; set; }
public string province { get; set; }
public string postalCode { get; set; }
public string phoneNumber { get; set; }
public string emailAddress { get; set; }
// This is a constructor
public Customer(string Name, string Address, string City, string Province, string PostalCode, string PhoneNumber, string EmailAddress)
{
name = Name; // Cannot determine if name is field or property
address = Address; // Cannot determine if address is field or property
city = City; // Cannot determine if city is field or property
province = Province; // Cannot determine if province is field or property
postalCode = PostalCode; // Cannot determine if postalCode is field or property
phoneNumber = PhoneNumber; // Cannot determine if phoneNumber is field or property
emailAddress = EmailAddress; // Cannot determine if emailAddress is field or property
}
}
Upvotes: 0
Views: 179
Reputation: 120410
When you declare an auto-implemented property:
public string Name { get; set; }
It is not necessary to create a backing field. The compiler creates a hidden (inaccessible) backing field for the property on your behalf that can only be accessed through the property's get
and set
accessors. You don't have to even think about it.
So, from your code above, just remove the fields that are duplicated by auto-implemented properties.
See: https://msdn.microsoft.com/en-us/library/bb384054.aspx
Upvotes: 3
Reputation: 728
When you declare Auto Property,the compiler generates the backing field for you.
ie. when you declare
public string Name { get; set; }
the compiler would have a code like
private string name; //Your backing Field.you don't need it manually.
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
Upvotes: 1