Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a {} Operator?

Tags:

c#

list

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

like image 257
Byyo Avatar asked Sep 24 '15 12:09

Byyo


People also ask

What does {} mean in JavaScript?

So, what is the meaning of {} in JavaScript? In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.


1 Answers

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.

like image 139
Yuval Itzchakov Avatar answered Oct 27 '22 00:10

Yuval Itzchakov