๐ŸŽ“ A1Learner
๐Ÿ”

C# Properties

A property is a member that controls reading and writing a value in a class. It looks like a field from outside the class.

An auto-property in action

Name is an auto-property. The short line gives both reading and writing.

using System;

class Person
{
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Name = "Hana";
        Console.WriteLine(person.Name);
    }
}

A full property

The Name property wraps the private name field. The set part stores the incoming value in that field.

using System;

class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Name = "Hana";
        Console.WriteLine(person.Name);
    }
}

A setter that checks

The Score setter stores only values that are zero or more. A negative value changes nothing.

using System;

class Player
{
    private int score;

    public int Score
    {
        get { return score; }
        set
        {
            if (value >= 0)
            {
                score = value;
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Player player = new Player();
        player.Score = 25;
        Console.WriteLine(player.Score);
        player.Score = -3;
        Console.WriteLine(player.Score);
    }
}

Example

using System;

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

    private double price;

    public double Price
    {
        get { return price; }
        set
        {
            if (value > 0)
            {
                price = value;
            }
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Product product = new Product();
        product.Name = "Notebook";
        product.Price = 12.5;
        Console.WriteLine(product.Name + " costs " + product.Price);
    }
}

Key points

  • A get part runs when the property is read.
  • A set part runs when the property is given a value.
  • The incoming value inside a set part is named value.
  • An auto-property writes the get and set parts in one short line.
  • A full property stores its data in a private backing field.
  • A backing field is a private field that holds the real value.
  • A set part can check value and refuse a bad one.

In this example, Name is an auto-property and holds Notebook. Price is a full property over the private price field. The setter accepts 12.5 because it is greater than zero. The last line prints the name and the price together.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What is the incoming value named inside a set part?