Click here to Skip to main content
11,805,035 members (66,719 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C# F#
Hi, what would be the closest equivalent F# code to a C# array of objects?


In C# I would create:

object[,] tableA = new object[30,2];
tableA [0, 0] = "dog";
tableA [0, 1] = 2;
tableA [1, 0] = "cat";
tableA [1, 1] = 31;

and so on ....

In F# I could create

let tableA_FS = Map( [("dog", 2); ("cat", 31)] );

However I cannot cast a map into a type object[,]

what is the closest type in F# to obj[,]?
Posted 2-Jul-12 7:06am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

In this particular case, you can use array2D:[^].

See also the section "Multidimensional Arrays" in the documentation page on F# arrays:[^].

tagad at 2-Jul-12 14:31pm
Hi SA,

thanks for your reply. An array2D can be specified in 1 type. In my example I am using string and integer as types. I am not clear from the reference you pointed how to initialize an array2D in 2 different types.

Sergey Alexandrovich Kryukov at 2-Jul-12 15:47pm
No, you are not using different types! You use one polymorphic type System.Object. It has nothing to do with the array rank, could be in single-dimensional array in exact same way. You can do exactly the same thing in F#.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

A possible way to do it is

let myArray2D : obj[,] = Array2D.create 2 2 (box())
myArray2D.[0,0] <- box("cc")
myArray2D.[0,1] <- box(2.0)

this has type obj[,]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 305
1 Sergey Alexandrovich Kryukov 268
2 CPallini 210
3 Richard Deeming 190
4 CHill60 150
0 OriginalGriff 3,255
1 Maciej Los 1,990
2 KrunalRohit 1,907
3 CPallini 1,855
4 Richard MacCutchan 1,227

Advertise | Privacy | Mobile
Web04 | 2.8.151002.1 | Last Updated 3 Jul 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100