CodeBlanks Logo Icon CodeBlanks

Auto-properties

C# course · Intermediate · Lesson 26/116

Learn auto-properties and assigning default values.

Auto-properties

Most of the time, a property's get and set bodies just return and write a private field. C# removes this boilerplate with an auto-property: public string Name { get; set; }.

The compiler generates a hidden field behind the scenes; you write no private field. Shorter, more readable. When you need validation, you can switch back to an explicit body; the interface does not change. Most properties in modern C# code are written as auto-properties.

Default values

You can give an auto-property a default value with an equals sign: public int Count { get; set; } = 0; or public string Label { get; set; } = "New";.

This value is assigned automatically when the object is created; no constructor is needed. Read-only auto-properties can also take a default: public string Code { get; } = "A100";. This is useful for values set at creation and never changed afterwards.

Exercise Add auto-properties to the Product class

Define a Product class. Add public string Name { get; set; } and public int Stock { get; set; } = 0; auto-properties. Inside Main create an instance with new Product { Name = "Pen" } and print Name and Stock.

Show example solution
Add two auto-properties to Product. In Main write Product p = new Product { Name = "Pen" }; Console.WriteLine(p.Name); Console.WriteLine(p.Stock);
Example solution:
using System;

class Product
{
    public string Name { get; set; }
    public int Stock { get; set; } = 0;
}

class Program
{
    static void Main()
    {
        Product p = new Product { Name = "Pen" };
        Console.WriteLine(p.Name);
        Console.WriteLine(p.Stock);
    }
}

Test yourself

  1. Match each declaration to its type

    { get; set; }
    Auto-property
    { get; }
    Read-only auto
    { get; set; } = 5;
    With default value
    private string name;
    Field
  2. Complete the auto-property

    public string Name { get; ____; }
    Show answer
    public string Name { get; set; }
  3. Which is an auto-property with default value 5?

    • public int Count { get; set; }
    • public int Count = 5;
    • public int Count() { return 5; }
    • public int Count { get; set; } = 5;
    Show answer

    public int Count { get; set; } = 5; — Correct. = 5 gives the auto-property a default value.

All lessons in Intermediate