Byyo
Byyo

Reputation: 2243

Is there a {} Operator?

You can use

List<string> sList = new List<string>() { "1", "2" };

to create a new List and add 2 items. The { "1", "2" }-part only works because List<T> has implemented a Add() method.

my question: is {} something like a operator and can it be overloaded e.g. to add items twice

Upvotes: 6

Views: 204

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149558

is {} something like a operator and can it be overloaded e.g. to add items twice

Any collection type which provides an Add method, built in or as an extension method (starting from C#-6), can use the collection initializer provided by the { } syntax. If your Add method adds the same item twice to that collection, then that is what it will do.

If you'd want the behavior of { } to change, you'd have to override or overload the Add method on the collection.

Some additional specification goodness (taken from this answer):

C# Language Specification - 7.5.10.3 Collection Initializers

The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer.

Upvotes: 12

Related Questions