Skip to content

Add non-throwing methods to Convert class #14081

@Alexx999

Description

@Alexx999

Convert class is the only method to convert boxed values to needed integer type. However, it throws exceptions, so it is too hard to implement behavior that matches simple explicit cast between integer types.
As a solution - add TryXXX methods to Convert class.

Additionally, it would be nice to have option to make Convert behave like explicit cast.
For example, this is valid:

int a = -1;
int b = (int)(uint)a;

But this is not:

int a = -1;
int b = Convert.ToInt32(Convert.ToUInt32(a));

This can be really useful when you process some data as "just some bytes" and you may get either signed or unsigned boxed value at input.
As a possible solution - add overload that accepts second boolean argument and acts like an explicit integer cast.

Example of this problems and required workaround can be seen in Enum class, in particular here:
https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Enum.cs#L207

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Runtimehelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions