Optional
Optional copied to clipboard
Should Optional implement IConvertable?
I'm looking for Convert
support in Optional, for use in Reflection, like:
Convert.ChangeType(value, type);
where value is of some type and type might be typeof(Option<T>)
, but it could be something else that implements IConvertable
.
This would depend on Option<T>
implementing IConvertable. I can make a PR for the inclusion of this functionality in the API.
I think it would make more sense to implement this for Conversion support rather than doing something else in reflection like adding a custom case in my own project's code for if the type is of Convert<>
and then calling Convert.Some<T>(value)
.
Is this within the scope of Option? Is there an argument to be made as to why it shouldn't be apart of the API? Is there an alternative way to implement this, or maybe something in the Optional API that offers casting between T
and Option<T>
through reflection?
Hi!
I’m afraid I don’t think this would be the right thing to do, and I’m not sure it would add enough value to be worth it.
Could you maybe eloborate a bit on your use cases for this?
/ Nils
API I'm working on accepts a string input and tokenizes that input. Those tokens get matched up to parameters for a series of methods defined by the developer using the API. The string input gets converted to the parameter's type before being passed to the method call.
Example input:
"field-name:Operator Name" modify "text:John Smith"
This gets tokenized into a few pairs, the value of each is "Operator Name", "John Smith". These values get passed into ChangeType
before being sent off to the Invoke
on the MethodInfo
for a particular method. I would be comfortable making a single-case change in my own code if I didn't feel like it would make sense to make this change in Optional itself.
I imagine the ToType
implementation, the important bit here, would look something simple like this:
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (!hasValue)
{
// throw exception if T is non-nullable,
// return null if T is nullable.
}
return Convert.ChangeType(value, conversionType, provider);
}
Which, I don't think would be a naive approach, and implementing the other methods for IConvertable would be similarly simple.