Thursday, March 31, 2011

Fields and Properties

Field Properties (private instance variables or 'Fields' could be encapsulted as 'Properties')

  1. Auto-implemented/Automatic Property. An anonymous backing-field is automatically created and the get and set accessors serve to provide field encapsulation only.Auto-implemented properties do not allow additional code in the get and set accessor methods.
  2. User-implemented Property  A user created backing-field has to be created and the get and set accessors can optionally have additional lines of code

Example of Auto-implemented Property (from an automatically created private anonymous-backing-field):

public string Name{get; set;}

Example of User-implemented property (from a User created private backing-field)

private string _empId;
public string EmpId
{
 get
 {
  return _empId;
  Console.WriteLine("Get Accessor Called");
 }


 set
 {
  _empId = value;
  Console.WriteLine("Set Accessor Called");
 }
}

PS : VS keyboard short cut to encapsute a private instance variable (or field) to a Property : (CTRL +R, CTRL + E)

No comments:

Post a Comment