Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement default method like StringCollection and some class does?

Tags:

c#

.net

While answering a question i came upon this

StringCollection sc = new StringCollection();

sc.Add("Foo");

But this can be written as

StringCollection sc = new StringCollection() {"Foo"};

and this cannot be written

StringCollection sc = new StringCollection() {new string[] {"Foo"} };

That means Add method is called and AddRange is not.

How can i make a class that can have this functionality of having a default method called while creating its object?

like image 747
Nikhil Agrawal Avatar asked Jul 27 '26 15:07

Nikhil Agrawal


2 Answers

It's called a Collection Initializer. The class must implement IEnumerable and have a public Add method.

The class can have multiple Add methods, e.g.

public class MyCollection : IEnumerable
{
    public void Add(string item) { ... }

    public void Add(string[] items) { ... }

    ...
}
like image 84
dtb Avatar answered Jul 29 '26 05:07

dtb


The code is a collection initializer : http://msdn.microsoft.com/en-us/library/bb384062.aspx

Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

The call to "Add" is generated by the compiler. So unless you write your own C# compiler, you cannot customize the behavior to call "AddRange".

like image 35
mathieu Avatar answered Jul 29 '26 05:07

mathieu