tags:

views:

97

answers:

2

Is there a function to check if an object is a list?

I did it like this:

try
    let x = unbox<list<obj>>(l)
    ....
with
   | _ -> ...

But i would like to check it with an if or match instead if it is possible.

+4  A: 

I'd use:

let isList o =
  let ty = o.GetType()
  if (ty = typeof<obj>) then false
  else 
    let baseT = ty.BaseType
    baseT.IsGenericType && baseT.GetGenericTypeDefinition() = typedefof<_ list>

if (isList o) then
  ...

This will identify lists containing any type of item (int lists, string lists, etc.).

kvb
+2  A: 

In case you know type of list elements you can use such code:

let is_list (x: obj) =
  match x with
  | :? list<int> -> printfn "int list"
  | :? list<string> -> printfn "string list"
  | _ -> printfn "unknown object"
ssp
I don't know the type, i have list<obj> but I tried it with :? list<obj> and i seams to work :D. Thanks
Razvi