LMB
LMB

Reputation: 1135

C# List-like instance initialization syntax

In C# i can write

var y = new List<string>(2) { "x" , "y" };

to get a List with "x" and "y" initialized.

How do I declare a class to accept this initialization syntax?

I mean, I want to write:

var y = new MyClass(2, 3) { "x" , "y" };

Upvotes: 1

Views: 518

Answers (4)

Ken
Ken

Reputation: 844

I'm not sure what (2,3) are supposed to indicate. I understand that it's your collection size in the first line. You can simply inherit from List or whatever structure you're needing to imitate.

Just tested this sample in LinqPad:

void Main()
{
    var list = new Foo{
        "a",
        "b"
    };

    list.Dump();
}

class Foo : List<string>{ }

Upvotes: 1

Marcus
Marcus

Reputation: 6107

Look at section 7.6.10.3 of the C# spec:

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.

A very simple example of this:

   class AddIt : IEnumerable
   {
      public void Add(String foo) { Console.WriteLine(foo); }

      public IEnumerator GetEnumerator()
      {
         return null; // in reality something else
      }
   }

   class Program
   {
      static void Main(string[] args)
      {
         var a = new AddIt() { "hello", "world" };

         Console.Read();
      }
   }

This will print "hello", followed by "world" to the console.

Upvotes: 6

Tod Hoven
Tod Hoven

Reputation: 476

As Marcus points out, the class must implement the IEnumerable interface and have an Add() method accessible to the caller.

In short, this skeleton example will work:

public class MyClass : IEnumerable
{
    public void Add(string item)
    {

    }

    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

Upvotes: 0

marc wellman
marc wellman

Reputation: 5886

Just initialize the fields of the class using the syntax:

// ...

Car myCar1 = new Car () { Model = "Honda", YearBuilt=2009 };
Car myCar2 = new Car () { Model = "Toyota", YearBuilt=2011 };

// ...

public class Car {

    public string Model;
    public int YearBuilt;
}

Upvotes: 0

Related Questions