Question

How to Give a C# Auto-Property an Initial Value

csharpconstructorgettersetterautomatic-properties

Question

How can you assign an initial value to a C# auto-property?

A common approach is to set the property inside the constructor:

class Person
{
    public Person()
    {
        Name = "Initial Name";
    }

    public string Name { get; set; }
}

Another option is to use the older full-property syntax with a backing field:

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

Is there a better or more modern way to give an auto-property a default value?

Short Answer

By the end of this page, you will understand how C# auto-properties can be initialized, when to use a constructor, when to use a property initializer, and when a backing field is still the right choice. You will also see practical examples and common mistakes to avoid.

Concept

In C#, an auto-property is a property where the compiler creates the hidden backing field for you.

Example:

public string Name { get; set; }

This is shorter and cleaner than writing a private field and a full get/set block yourself.

The main question is: how do you give that property a default value?

There are three common approaches:

  1. Set it in the constructor
  2. Use a property initializer
  3. Use a backing field with full property syntax

Modern C# approach

In modern C#, the simplest way is usually a property initializer:

public string Name { get; set; } = "Initial Name";

This is the most direct way to give an auto-property a default value.

Why this matters

Default values are useful when:

  • an object should start in a valid state
  • you want to reduce repeated constructor code
  • a property should have a sensible fallback value
  • you want cleaner and more readable class definitions

When each approach makes sense

  • Property initializer: best for simple constant or straightforward default values
  • Constructor: best when the value depends on constructor parameters or setup logic
  • Backing field: best when you need custom logic inside get or set

In short, if you only want a default value and do not need extra logic, auto-property initializer syntax is usually the best choice.

Mental Model

Think of an object like a form being filled out when it is created.

  • A property is one field on the form.
  • A default value is what is already written there before anyone edits it.
  • An auto-property means C# stores that value for you behind the scenes.

So this:

public string Name { get; set; } = "Initial Name";

means:

  • create a Name field on the form
  • if nobody provides a value yet, start with "Initial Name"

You do not need to manually build the storage box unless you need special behavior.

Take Quiz

Syntax and Examples

Basic auto-property initializer

class Person
{
    public string Name { get; set; } = "Initial Name";
}

This creates an auto-property and assigns a default value.

Using a constructor instead

class Person
{
    public Person()
    {
        Name = "Initial Name";
    }

    public string Name { get; set; }
}

This works well when initialization needs logic or depends on other values.

Read-only auto-property initializer

If a property should only be set during object creation, you can use a getter-only property:

class Person
{
    public string Name { get; } = "Initial Name";
}

This means Name starts with "Initial Name" and cannot be changed later.

When a backing field is still useful

class Person
{
    private string name = "Initial Name";

    public string Name
    {
        get { return name; }
        set
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                name = value;
            }
        }
    }
}

Use this style if you need validation or extra logic in the setter.

Example with object creation

class Person
{
    public string Name { get; set; } = "Initial Name";
}

Person p1 = new Person();
Console.WriteLine(p1.Name); // Initial Name

Person p2 = new Person { Name = "Alice" };
Console.WriteLine(p2.Name); // Alice

The default value is used unless another value is assigned.

Step by Step Execution

Consider this example:

class Person
{
    public string Name { get; set; } = "Initial Name";
}

var person = new Person();
Console.WriteLine(person.Name);

What happens step by step

  1. The Person class is defined.
  2. The Name auto-property is declared.
  3. The initializer = "Initial Name" tells C# to assign that value when a new object is created.
  4. new Person() creates a new Person object.
  5. During creation, Name is initialized to "Initial Name".
  6. Console.WriteLine(person.Name) reads the property.
  7. The output is:
Initial Name

With an override value

var person = new Person
{
    Name = "Maria"
};

Console.WriteLine(person.Name);

Step by step:

  1. new Person() creates the object.
  2. Name first gets the default value "Initial Name".
  3. The object initializer then sets Name to "Maria".
  4. The final printed value is Maria.

So the default is the starting value, not a permanent one.

Real World Use Cases

Default property values appear in many real programs.

User and profile models

public class UserProfile
{
    public string DisplayName { get; set; } = "New User";
    public bool IsActive { get; set; } = true;
}

This avoids null or unset values for common fields.

Configuration objects

public class AppSettings
{
    public int TimeoutSeconds { get; set; } = 30;
    public string EnvironmentName { get; set; } = "Development";
}

Defaults make configuration safer when not every value is provided.

API request or response models

public class CreateOrderRequest
{
    public string Currency { get; set; } = "USD";
    public int Quantity { get; set; } = 1;
}

This gives predictable behavior when clients omit optional values.

Collections

public class Team
{
    public List<string> Members { get; set; } = new List<string>();
}

This prevents null collection problems and lets code add items immediately.

Take Quiz

Real Codebase Usage

In real codebases, developers usually choose the initialization style based on intent.

Common pattern: simple defaults in property initializers

public class JobOptions
{
    public bool Enabled { get; set; } = true;
    public int RetryCount { get; set; } = 3;
}

This keeps defaults close to the property definition.

Constructor for dependent values

public class Person
{
    public Person(string firstName, string lastName)
    {
        FullName = firstName + " " + lastName;
    }

    public string FullName { get; }
}

Here the value depends on constructor inputs, so a constructor is the right tool.

Validation with backing fields

public class Product
{
    private decimal price = 1.0m;

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

This is useful when the property must reject invalid assignments.

Guarding against null collections

public class Report
{
    public List<string> Errors { get; set; } = new List<string>();
}

This pattern is extremely common because it prevents null checks everywhere else.

Using init for safer object setup

In newer C#, developers often combine defaults with init:

public class Person
{
    public string Name { get; init; } = "Initial Name";
}

This allows assignment during object creation, but not after.

Common Mistakes

1. Writing full property syntax when it is not needed

If you do not need custom logic, this is unnecessarily verbose:

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

Prefer:

public string Name { get; set; } = "Initial Name";

2. Assuming the default value cannot be changed

This property can still be updated later:

public string Name { get; set; } = "Initial Name";

If you want it fixed after creation, use:

public string Name { get; } = "Initial Name";

or

public string Name { get; init; } = "Initial Name";

3. Forgetting that object initializers run after defaults

var person = new Person { Name = "Bob" };

Even if Name has a default value, "Bob" replaces it.

4. Leaving collections uninitialized

Broken example:

public class Team
{
    public List<string> Members { get; set; }
}

This can cause a NullReferenceException if you do:

team.Members.Add("Alice");

Safer version:

public class Team
{
    public List<string> Members { get; set; } = new List<string>();
}

5. Using a constructor for simple constants everywhere

A constructor is not wrong, but this:

public Person()
{
    Name = "Initial Name";
}

is often less clear than:

public string Name { get; set; } = "Initial Name";

Use the simplest tool that matches the need.

Comparisons

ApproachExampleBest forProsCons
Auto-property initializerpublic string Name { get; set; } = "Initial Name";Simple default valuesShort, clear, modernNot ideal for complex setup logic
Constructor assignmentName = "Initial Name";Values based on parameters or logicFlexibleMore boilerplate for simple defaults
Backing field + full propertyprivate string name = "Initial Name";Validation or custom getter/setter logicFull controlMore verbose

Auto-property initializer vs constructor

  • Use initializer when the default is simple and always the same.
  • Use constructor when the value depends on other inputs.

Auto-property vs backing field

  • Use auto-property when you only need storage.
  • Use backing field when you need validation, transformation, caching, or side effects.
Take Quiz

Cheat Sheet

Quick syntax

Auto-property with default value

public string Name { get; set; } = "Initial Name";

Read-only auto-property with default value

public string Name { get; } = "Initial Name";

Init-only property with default value

public string Name { get; init; } = "Initial Name";

Constructor-based initialization

public Person()
{
    Name = "Initial Name";
}

Rules of thumb

  • Use property initializers for simple defaults.
  • Use constructors when defaults depend on parameters or logic.
  • Use backing fields when you need custom get or set behavior.
  • Initialize collections to avoid null.
  • Object initializers can override default property values.

Common examples

public bool IsActive { get; set; } = true;
public int RetryCount { get; set; } = 3;
public List<string> Tags { get; set; } = new List<string>();

Edge case reminder

This:

public string Name { get; set; } = "Initial Name";

sets a starting value, but the property can still be changed later unless it is get-only or init-only.

FAQ

Can you initialize an auto-property directly in C#?

Yes. In modern C#, you can write:

public string Name { get; set; } = "Initial Name";

Is using the constructor still valid for property defaults?

Yes. It is still a good choice when the value depends on constructor parameters or setup logic.

When should I use a backing field instead of an auto-property?

Use a backing field when you need custom logic in the getter or setter, such as validation or transformation.

Does a property initializer run before or after an object initializer?

The property initializer sets the default first. Then the object initializer can overwrite it.

Can a read-only property have a default value?

Yes:

public string Name { get; } = "Initial Name";

What is the best way to initialize a list property in C#?

Usually like this:

public List<string> Items { get; set; } = new List<string>();

This prevents null-reference issues.

Is the older full-property syntax wrong?

No. It is still useful when you need a backing field and custom logic. It is just not necessary for simple defaults.

Take Quiz

Mini Project

Description

Create a small C# class model for an application user profile. The project demonstrates how to assign default values with auto-property initializers, when those values can be overridden, and how to safely initialize collections.

Goal

Build a UserProfile class that starts with sensible default values and can still be customized when an object is created.

Requirements

  • Create a UserProfile class with at least three auto-properties.
  • Give default values to a string property, a boolean property, and a collection property.
  • Create one object using only defaults.
  • Create another object that overrides at least one default value.
  • Print both objects to show the final property values.
Take Quiz

Keep learning

Related questions

View more