brinch
brinch

Reputation: 2614

How to declare an array of objects in F#?

I have this declaration of an array in C#:

object[] objects = { "myString", 12, 2.06, null, "otherString" };

Now I want to declare a similar array in F#, so I try:

let objects = ["myString"; 12; 2.06; null; "otherString"]

But this gives me compile errors:

"This expression was expected to have type string but here has type int"

and

"This expression was expected to have type string but here has type float"

for values 12 and 2.06.

How should I proceed to create a similar array in F#?

Upvotes: 2

Views: 2836

Answers (1)

V.B.
V.B.

Reputation: 6382

In your code you are declaring a list:

let objects : obj list = ["myString"; 12; 2.06; null; "otherString"]

an array would be:

let objects : obj[] = [|"myString"; 12; 2.06; null; "otherString"|]

just add a type annotation :obj list or : obj[] to any of those, otherwise F# infers the type from the first element.

Upvotes: 4

Related Questions