Skip to content

CSharp Properties Basics Naming

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Properties: Basics and Naming

This lesson introduces properties in C#, plus some basic naming conventions. Properties are the idiomatic way to expose data from classes in .NET.

Related wiki pages:

  • General C# overview: CSharpBible.md
  • Libraries and data structures: CSharpBible-Libraries.md

Official docs:


1. Auto-properties

The most common property form is the auto-property:

public class Product
{
    public string Name { get; set; }   // nullable reference type depending on project settings
    public decimal Price { get; set; }
}

Usage:

var product = new Product
{
    Name = "Example Product",
    Price = 9.99m
};

Console.WriteLine($"Product Name: {product.Name}");
Console.WriteLine($"Product Price: {product.Price}");

2. Properties with get and set

You can add logic to get/set instead of using auto-properties:

public class Person
{
    private int _age;

    public string Name { get; set; } = string.Empty;

    public int Age
    {
        get => _age;
        set
        {
            if (value < 0)
                throw new ArgumentOutOfRangeException(nameof(value));

            _age = value;
        }
    }
}

This pattern allows validation and encapsulation of internal state.


3. Read-only and init-only properties

Read-only:

public class Configuration
{
    public string Environment { get; } = "Production";
}

Init-only (C# 9+):

public class User
{
    public string Name { get; init; } = string.Empty;
}

var user = new User { Name = "Alice" }; // ok
// user.Name = "Bob"; // compile error: init-only

4. Naming conventions (brief)

  • Types and properties: PascalCase (e.g. ProductName, CustomerAddress)
  • Local variables and parameters: camelCase (e.g. productName, customerAddress)

These follow the .NET naming guidelines and match the rest of this wiki (see also CSharpBible.md).


5. Next steps

  • Explore properties in context of classes and records in CSharpBible.md.
  • Look for examples that use properties in MVVM view models in CSharpBible-MVVM-Basics.md and CSharpBible-MVVM-Standard.md.
  • Continue with object initialization patterns in CSharp-Properties-Init.md (once created) and nullable handling in CSharp-Nullability-Basics.md (once created)

Clone this wiki locally