Comparison of type f #

I am trying to find out if obj is returned by a call of a specific type. Here is my code:

type MyType<'T>= val mutable myArr : array val mutable id : int val mutable value : 'T 

and in some method that has MyType in scope ...

 let a = someFunThatReturnsObj() // a could be of type MyType 

How can I determine if the type is MyType?

+6
generics types f #
source share
2 answers
 match a with | :? MyType<int> as mt -> // it a MyType<int>, use 'mt' | _ -> // it not 

If you only need MyType<X> for unknown X , then

 let t = a.GetType() if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<MyType<int>> then // it is 
+5
source share

I don’t think it’s so simple (remember that I’m naive), consider the following scenario in which

1) we use generics on several types 2) we do not have type information for the object, so it is part of the obj type function, as in some datacontract / serialization.NET libraries.

I reworked my suggestion to use reflection:

 type SomeType<'A> = { item : 'A } type AnotherType<'A> = { someList : 'A list } let test() = let getIt() : obj = let results : SomeType<AnotherType<int>> = { item = { someList = [1;2;3] }} upcast results let doSomething (results : obj) = let resultsType = results.GetType() if resultsType.GetGenericTypeDefinition() = typedefof<SomeType<_>> then let method = resultsType.GetMethod("get_item") if method <> null then let arr = method.Invoke(results, [||]) if arr.GetType().GetGenericTypeDefinition() = typedefof<AnotherType<_>> then printfn "match" getIt() |> doSomething 

There seems to be a more natural way to do this ...

+1
source share

All Articles