1

might be stupid question, but I would like to initialize my array of objects like this:

FooBar[] fooBars = new FooBars[]
{
    {"Foo", "Bar"},
    {"Foo", "Bar"}
};

where FooBar is:

public class FooBar
{
    public string foo;
    public string bar;
}

I've tried inherit from CollectionBase and add Add(string) method, or string[] operator, but none of those works :/

  • Ofc dictionaries work like that: Dictionary dic = new Dictionary() {{"foo", "bar"}}; – blackmaciek Oct 19 '17 at 11:21
  • https://msdn.microsoft.com/en-us/library/83h9yskw(v=vs.110).aspx – Mike Cheel Oct 19 '17 at 11:25
  • If you have decalred an array of FooBars, then you also need to populate it with instances of FooBars, so you would have to do `new Foobar()`, and then fill in the `foo` and `bar` properties. However a better way would be to pass those in the FooBar constructor. Additionally if you want to use a string pair, consider using a dictionary. – pkanev Oct 19 '17 at 11:31
  • If think you are missing an inheritance from IEnumerable - see this answer: https://stackoverflow.com/a/9570300/1632576 – TeaHoney Oct 19 '17 at 11:53

2 Answers2

4

Is this what you are looking for? I don't understand exactly what you're asking.

You can play a bit with it in this fiddle if you want to.

public class FooBar
{
    public FooBar(string foo, string bar)
    {
        this.foo = foo;
        this.bar = bar;
    }

    public string foo;
    public string bar;
}

public static void Main(String[] args)
{
    FooBar[] fooBars = new FooBar[] {
        new FooBar("Foo", "Bar"), 
        new FooBar("Foo", "Bar")
    };
}
rmjoia
  • 962
  • 12
  • 21
0

You can cheat a bit by giving class FooBar an implicit constructor (requires latest version of C# for the tuple support):

public class FooBar
{
    public string foo;
    public string bar;

    public static implicit operator FooBar((string, string) init)
    {
        return new FooBar{ foo = init.Item1, bar = init.Item2 };
    }
}

Then code like this will work:

var fooBars = new FooBar[]
{
    ("Foo1", "Bar1"),
    ("Foo2", "Bar2")
};

OR

FooBar[] fooBars = 
{
    ("Foo1", "Bar1"),
    ("Foo2", "Bar2")
};

And then:

foreach (var fooBar in fooBars)
    Console.WriteLine($"foo = {fooBar.foo}, bar = {fooBar.bar} ");

which seems fairly close to what you're aiming for (albeit with parentheses instead of braces).

But normally you'd just use the new FooBar("Foo", "Bar") syntax as per the other answer.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • This helps a lot, not exacly what I was looking for, but looks cool ;) – blackmaciek Oct 23 '17 at 09:38
  • @blackmaciek Please be aware that it's not a very efficient solution, since you will be constructing a temporary tuple for each call to the `FooBar` constructor, which would NOT be necessary if you use the normal `new Foobar(...)` syntax. – Matthew Watson Oct 23 '17 at 09:59