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

Properties

In this page:

  1. Properties

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}");
    }
}
🔒

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.