Rather than boxing back to object and then having to cast to type; it would be good to have a change type that returns the type:
partial class Convert
{
[return: NotNullIfNotNull("value")]
public static T? ChangeType<T>(object? value);
[return: NotNullIfNotNull("value")]
public static T? ChangeType<T>(object? value, IFormatProvider? provider);
}
Not sure on nullable return type for structs?
If we make object? ChangeType(object? value, TypeCode typeCode) inlineable Jit should be able to eliminate the intermediate boxing I guess. Isn't typeCode a constant in most use-cases?
It's not the first time I am thinking of a special attribute InlineIfConst.. I know JIT takes constant input into account for inlining budget but it won't help with large methods.
public static object? ChangeType(object? value, Type conversionType) is more likely the called overload, and then it has to do a look up to get the typecode falling through a bunch of if tests.
Then when you use it in the generic as well as reboxing the output you then have to cast it to the type
e..g
T value = (T)Convert.ChangeType(inputValue, typeof(T));
[then it has to do a look up to get the typecode](https://github.com/dotnet/runtime/blob/3b72a4d7013abd36b0f2e145f44df85c43fc83aa/src/libraries/System.Private.CoreLib/src/System/Convert.cs#L287-L352) falling through a bunch ofif` tests.
yeah but if typecode is a const -- all those ifs will be easily eliminated 馃檪
Then when you use it in the generic as well as reboxing the output you then have to cast it to the type
e..gT value = (T)Convert.ChangeType(inputValue, typeof(T));Jit eliminates boxing for
(T)(object)varOfT, see https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBDAzgWwB8ABAJgEYBYAKGIAYACAZQAtsoAHAGW2ADoASgFcAdhgCW+GAG4aNYgGYGZBgGEGAbxoMdDbboDaAKXEYA4jBEwo4sAAoMATw4wIAMzvixASjQMnLu6ePt4Auvo6igwAKgAiuBgMALIAPNFMUGB+cQkAfHbpmf7eEZqlusoA7AwF8RjedhDAAFYwYPUYstQVAL40PUA=
As a developer/user would I prefer to write:
T value = (T)Convert.ChangeType(inputValue, typeof(T));
Or
T value = Convert.ChangeType<T>(inputValue);
An the implementation of the second done via generics could be more efficient than the first using type?
Most helpful comment
As a developer/user would I prefer to write:
Or
An the implementation of the second done via generics could be more efficient than the first using type?