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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With