Saturnix
Saturnix

Reputation: 10554

No best type found for implicitly-typed array

Can someone explain me why this code:

var marketValueData = new[] {
    new { A = "" },
    new { A = "" },
    new { B = "" },
};

Is giving me the error:

No best type found for implicitly-typed array

while this one works perfectly fine:

var marketValueData = new[] {
    new { A = "" },
    new { A = "" },
    new { A = "" },
};

Apart from a different property (B in the last entry of the first example), they are the same. Yet the first one is not compiling. Why?

Upvotes: 36

Views: 22921

Answers (4)

I had a similar problem in a code line like this

sqwOraContext.save(new[] { student, course });

student and course inherit both from SQWEntity but the compiler for some reason doesn't check the base type. Only setting the array type to SQWEntity resolved the error.

sqwOraContext.save(new SQWEntity[] { student, course });

Of course there is no need to specify the type in a line like this where student1, student2 are of the same type.

sqwOraContext.save(new[] { student1, student2 });

Upvotes: 2

Yas
Yas

Reputation: 5491

You can use:

var marketValueData = new object[] {
    new { A = "" },
    new { A = "" },
    new { B = "" },
    ...,
};

Upvotes: 47

Norbert Pisz
Norbert Pisz

Reputation: 3440

Anonymous types must be the same. Just change B to A.

Upvotes: 5

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

It's because you have two different anonymous types in the first example, the definition of the last item is different than the other ones.

In the first example , one containing an A property and one containing a B property, and the compiler can't figure out the type of array. In the second example there is one anonymous type, containing only A.

I think it's a typo, so you can change B to A in last entry in first example

From MSDN:

You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer.

Upvotes: 38

Related Questions