Properties

View saved

Auto-properties

Properties look like fields from the outside but can control access.

class Course
{
    public string Title { get; set; } = "";
    public int Lessons { get; set; }
}

var c = new Course { Title = "C#", Lessons = 18 };
Console.WriteLine(c.Title);

Read-only from outside

Use private set or init to limit mutation.

public string Id { get; private set; } = Guid.NewGuid().ToString();

Computed properties

A get-only property can derive a value.

public string Summary => $"{Title} ({Lessons} lessons)";

Property habits

  • Prefer properties over public fields
  • Validate in setters when rules matter
  • Use object initializers for clear construction
  • Init-only properties work well with immutable styles

Comments

One comment per signed-in account. Comments are saved with this page’s URL.