Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection to find out if property is of option type

Tags:

reflection

f#

I am filling some object's fields with data using reflection. As my object is of F# type, it has some Option fields. In case of option

property.SetValue(object, newValue)

reasonably fails, because it needs

property.SetValue(object, Some(newValue))

Hence, I am trying to find out if a property is of type Option. I can do it like this:

let isOption (p:PropertyInfo) = p.PropertyType.Name.StartsWith("FSharpOption")

But there must be some better way, must it not? And I must say it is strange to me that there's no method IsOption in FSharpType.

like image 956
Rustam Avatar asked Dec 20 '13 04:12

Rustam


1 Answers

You can use something like this:

let isOption (p:PropertyInfo) = 
    p.PropertyType.IsGenericType &&
    p.PropertyType.GetGenericTypeDefinition() = typedefof<Option<_>>

Basically, GetGenericTypeDefinition returns the generic type of the property without any type parameters. And typedefof does something very similar, only using compile-time type information. In this case, it will return Option<>, without any parameters. You can then simply compare them to see if they are the same type.

like image 109
p.s.w.g Avatar answered Oct 13 '22 01:10

p.s.w.g