CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.

Home Page:https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add Box<T>.GetValue() extension method

AlexRadch opened this issue · comments

Overview

Now to get the boxed value, we need to use an implicit cast to the boxed type. The compiler cannot always make such an implicit cast, especially for generic methods. At first, the compiler tries to pass a Box instance to a generic method and does not perform implicit type casting. In this case, developers are forced to call an explicit instance cast to the boxed type. For example Assert.AreEqual(value, (boxedType)box). I believe that it will be more convenient for developers to use the GetValue() extension method to get the boxed value, rather than calling an explicit cast to the boxed type.

Using the GetReference() method is less preferable because this method is unsafe and allows the boxed value to be modified. The GetReference() method is intended primarily for rare scenarios where changing a boxed value without creating a new instance can improve code performance and the developer understands why he is using this method.

So I suggest adding an extension method Box<T>.GetValue() to safely get the boxed value. This method will be safe, developer-friendly, and compiler-friendly in generic methods.

API breakdown

public static class BoxExtensions
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static T GetValue<T>(this Box<T> box) where T : struct => (T)box;
}

Usage example

Assert.AreEqual(value, box.GetValue());

Breaking change?

No

Alternatives

Use the dangerous GetReference() method.

Additional context

No response

Help us help you

Yes, I'd like to be assigned to work on this item

Closing this due to the same reason as in #822 (comment). We plan on just removing this type entirely 🙂