← Back to C# Course | Chapter 6: OOP Basics | Lesson 4 of 7

Properties

Properties are guarded windows into an object's data: you can look at a value or change it, and the class can check the change first. It is like a receptionist who handles requests for the office.

In this page:

  1. Properties
Syntax
csharp
class ClassName
{
    public type AutoProperty { get; set; }

    private type field;
    public type PropertyName
    {
        get { return field; }
        set { field = value; }
    }
}

Properties

Properties expose a class's data through get and set accessors, giving you control over how a field is read or written while still looking like a plain field to callers.

Auto-implemented properties ({ get; set; }) skip the backing field entirely for simple cases. Properties are the idiomatic C# alternative to writing manual getter/setter methods.

Note: Use { get; private set; } to make a property publicly readable but only settable from inside the class.

Example: Properties

markup
using System;

class Product
{
    public string Name { get; set; }
    private decimal price;

    public decimal Price
    {
        get { return price; }
        set { price = value < 0 ? 0 : value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Product p = new Product { Name = "Pen", Price = -5 };
        Console.WriteLine($"{p.Name}: {p.Price}");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing a property whose setter calls itself, such as set { Name = value; }, causing infinite recursion.
  2. Using a public field where a property with validation is needed.
  3. Forgetting get or set and then being unable to read or write the property.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.