Auto Implemented feature allows you to define the properties in more concise way. You need not to explicitly declare a variable & create a property for it. Complier internally declares a variable & generates code to access that variable though the property.
Old Style of defining the properties
class Emp
{
// Variable/fields
int salary;
string name;
/// <summary>
/// Property to access salary field
/// </summary>
public int Salary
{
get { return salary; }
set { salary = value; }
}
/// <summary>
/// Property to access name field
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
}
New way of defining properties
Following is new way to use properties. From functionality point of view both are same. We need not to declare a variable, complier would do it internally.
class Emp
{
/// <summary>
/// Property
/// </summary>
public int Salary { get; set; }
/// <summary>
/// Property
/// </summary>
public string Name { get; set; }
}
Notes
4. Auto implemented must have both getter & setter field. For e.g. following code would not work
// This would not compile
public int Salary { set; }
// Read only property
public string Name { get; private set; }
// Write only property
public string Name { private get; set; }
// This would not compile
public string Name { private get; private set; }
No comments:
Post a Comment