Runtime: [Api Proposal] Generic Convert.ChangeType

Created on 9 Feb 2020  路  6Comments  路  Source: dotnet/runtime

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:

Proposed API

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);
}

Questions

Not sure on nullable return type for structs?

api-suggestion area-System.Runtime

Most helpful comment

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?

All 6 comments

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..g

T 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?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yahorsi picture yahorsi  路  3Comments

jchannon picture jchannon  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments

matty-hall picture matty-hall  路  3Comments

aggieben picture aggieben  路  3Comments