2

I came across a property of the type String array during my work and decided to be smart about it and add an anonymous array of values to it, since I didn't need an array of values I was only going to use once sticking around. To my surprise though, it's not possible?

class Foo
{
    public String[] bar { get; set; }
}

static void Main(string[] args)
{
   Foo foo = new Foo();
   String[] arr = { "val1", "val2", "val3" };
   foo.bar = arr;
   foreach (String bar in foo.bar)
    {
            Console.WriteLine(bar);
    }
 }

Not surprisingly outputs: "val1" "val2" "val3"

But!

static void Main(string[] args)
{
    Foo foo = new Foo();
    foo.bar = {"val1", "val2", "val3"};
}

Throws all kinds of nasty compiler errors.

Googled turned up short of an answer, so I'm turning to SO. Why is this not possible?

1
  • 4
    In what way is this "anonymous"? It's not using anonymous types, or anonymous methods... nothing in this code corresponds to any use of an "anonymous" term in C#, as far as I'm aware. Commented Aug 20, 2013 at 8:17

1 Answer 1

4

You haven't told it that you want an array; in your original line:

String[] arr = { "val1", "val2", "val3" };

it has enough information to understand what you want, but outside of such declarations with initializers more is needed.

static void Main(string[] args)
{
    Foo foo = new Foo();
    foo.bar = new[]{"val1", "val2", "val3"};
}

or (being much more specific, but functionally identical):

static void Main(string[] args)
{
    Foo foo = new Foo();
    foo.bar = new string[3]{"val1", "val2", "val3"};
}

I'd say the first is preferable; less to get wrong ;p

As Jon notes; if you want to be even less verbose you can use an object initializer:

static void Main()
{
    var foo = new Foo { bar = new[] {"val1", "val2", "val3"} };
}
Sign up to request clarification or add additional context in comments.

1 Comment

You might want to mention the option of an object initializer, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.