2.7.5 Converting a Public Field to a Property

Converting a Public Field to a Property

Replace an exposed Player field with a property and private backing field. Matching the public name can preserve caller syntax while changing what that syntax executes.

Inspect the existing field and callers
Old definition
public class Player
{
    public int JerseyNumber;
}

Callers can read or write JerseyNumber directly. Find All References before editing so you can check every use after the conversion.

Preserve the public name deliberately

Replace the entire old definition with the complete property version from the accessor lesson.

Caller syntax can remain the same
Player jordan = new Player();
jordan.JerseyNumber = 7;
int displayedNumber = jordan.JerseyNumber;

The caller now invokes accessors instead of accessing a public field. Keep JerseyNumber capitalized as the public property and jerseyNumber lowercase as private storage. Do not leave the original field beside a property with the same name.

Separate conversion from new restrictions
  1. Build after replacing the definition.
  2. Assign 7 and read it back; expect 7.
  3. Place breakpoints inside the getter and setter to confirm they execute.
  4. If adding restrictions, specify and check accepted values, boundary values, and rejected values separately.
Apply the idea
Check your understanding