CodeBlanks Logo Icon CodeBlanks

Fields and properties

C# course · Intermediate · Lesson 2/116

Learn fields, properties and auto-property usage.

Fields

Variables declared in a class body are called fields. Fields hold the object's data. In a Product class, public string name; is a field.

Fields take an access modifier: public from anywhere, private only inside the class. For encapsulation, most fields are private and exposed through properties. Fields use lowercase, properties use PascalCase.

Properties

Properties read like fields but work like methods behind the scenes. get is the read accessor, set is the write accessor. The most common form is the auto-property:

public string Name { get; set; }. This line tells the compiler to generate a hidden field and handle reading and writing automatically. Less code, stronger encapsulation. Property names use PascalCase: Name, Price, IsActive.

Exercise Add properties to the Product class

Define a Product class with public string Name { get; set; } and public decimal Price { get; set; } auto-properties. Inside Main create an instance, set Name to "Pen" and print Name.

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

class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

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

Test yourself

  1. Complete the field declaration

    class Product { public string ____; }
    Show answer
    class Product { public string name; }
  2. Which is a valid auto-property?

    • public string Name;
    • public string Name { get; set; }
    • public string Name = get; set;
    • public Name { }
    Show answer

    public string Name { get; set; } — Correct. { get; set; } is the auto-property syntax.

  3. Match each declaration to its type

    public string name;
    Field
    public string Name { get; set; }
    Auto-property
    new Product()
    Instance creation
    product.Name
    Property access

All lessons in Intermediate