0
0
CsharpHow-ToBeginner · 3 min read

How to Use Property in C#: Syntax and Examples

In C#, a property is a member that provides a flexible way to read, write, or compute the value of a private field. You define a property using get and set accessors inside a class to control access to data safely and cleanly.
📐

Syntax

A property in C# has a name and type like a field, but it uses get and set blocks to control reading and writing values. The get accessor returns the value, and the set accessor assigns a value.

You can make a property read-only by only providing get, or write-only by only providing set.

csharp
public class Person
{
    private string name; // private field

    public string Name  // property
    {
        get { return name; }  // read value
        set { name = value; } // write value
    }
}
💻

Example

This example shows a Person class with a property Name. It demonstrates setting and getting the property value.

csharp
using System;

public class Person
{
    private string name;

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

public class Program
{
    public static void Main()
    {
        Person person = new Person();
        person.Name = "Alice";  // set property
        Console.WriteLine(person.Name);  // get property
    }
}
Output
Alice
⚠️

Common Pitfalls

One common mistake is forgetting to use a backing field, which causes infinite recursion if you use the property name inside its own get or set. Another is not controlling access properly, which can expose data unintentionally.

Also, using auto-properties without understanding they create hidden backing fields can confuse beginners.

csharp
public class Wrong
{
    private string name;

    public string Name
    {
        get { return Name; }  // WRONG: calls itself recursively
        set { Name = value; } // WRONG: calls itself recursively
    }
}

public class Right
{
    private string name;

    public string Name
    {
        get { return name; }  // Correct: uses backing field
        set { name = value; }
    }
}
📊

Quick Reference

  • Property syntax: Use get to read and set to write.
  • Auto-properties: Use public string Name { get; set; } for simple cases without explicit fields.
  • Access control: You can make get or set private to restrict access.
  • Read-only property: Provide only get.

Key Takeaways

Properties in C# use get and set accessors to control access to private data.
Always use a backing field inside get and set to avoid infinite recursion.
Auto-properties simplify code by creating hidden backing fields automatically.
You can control access by making get or set private or omitting one accessor.
Properties make your class data safer and easier to maintain.