Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Properties instead of public fields

A property looks like a value from outside and like a method inside. It is the polite way to expose data from a class.

A property in C#

C#
public class Lesson
{
    private int minutes;

    public int Minutes
    {
        get { return minutes; }
        set
        {
            if (value >= 0)
            {
                minutes = value;
            }
        }
    }
}

Why not just a public field

  • A property can reject a bad value, as the setter above rejects a negative number.
  • A property can be read only or write only when that is the right rule.
  • The storage can change later without breaking every caller.
Naming habit. A property uses a capital first letter and its backing field uses a lower case one. The pattern makes it obvious which is which at a glance.

When objects are no longer needed, the runtime reclaims them. That process is garbage collection.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.