user2961852
user2961852

Reputation: 31

Array property initialization

How can I initialize an array property?

Tried this:

feeds = new List<Feed>();
feeds.Add(new Feed() { Names = { "Cluj Approach", "Cluj Tower" }, Frequencies = { 117.25 } });

with the Feed class:

class Feed
{
    public string[] Names { get; set; }
    public float[] Frequencies { get; set; }
    public float Latitude { get; set; }
    public float Longitude { get; set; }
}

and it says it can't initialize an object of type string[] with a collection initializer. Any ideas ?

Upvotes: 3

Views: 5658

Answers (2)

Servy
Servy

Reputation: 203842

You need to actually new up the array, rather than just using braces:

new Feed() { Names = new string[] { "Cluj Approach", "Cluj Tower" } //...

You can at most simplify it to:

new Feed() { Names = new [] { "Cluj Approach", "Cluj Tower" } //...

and have the type inferred.

Upvotes: 3

Alireza
Alireza

Reputation: 10476

Try

feeds.Add(new Feed() { Names = new[] { "Cluj Approach", "Cluj Tower" }, Frequencies = new[] { 117.25f } });

Also note f in 117.25f.

Upvotes: 8

Related Questions