CaptainCrunch
CaptainCrunch

Reputation: 91

new() usage in methods for C#

What exactly does it mean when assigning new() to a property? I found some examples of seeing new usage in method calls but not like the below.

public ObservableCollection<Customer> Customers { get; } = new();

Upvotes: 0

Views: 97

Answers (2)

Guru Stron
Guru Stron

Reputation: 143453

This is a target-typed new expression (introduced in C# 9) and is equivalent to:

public ObservableCollection<Customer> Customers { get; } = new ObservableCollection<Customer>();

So the Customers is an auto implemented property which initialized to a newly created instance of ObservableCollection<Customer>.

Upvotes: 3

ScottishTapWater
ScottishTapWater

Reputation: 4846

It's target-typed new, essentially it will create an object of whatever the left of the operand is.

In the case of auto-properties, it will assign a new instance of the type of that property, to the property.

So if we strip away all of the syntactic sugar, what you've essentially got is:

private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();

public ObservableCollection<Customer> Customers
{
    get
    {
        return _customers;
    }
}

Incidentally, you can use a target-typed new almost anywhere there's a well-known type, not just on auto-properties.

Upvotes: 5

Related Questions