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.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.99k stars 294 forks source link

Feature request: Add Box<T>.TryGetFrom method that return just nullable Box<T> instance without a boolean flag of success. #790

Closed AlexRadch closed 8 months ago

AlexRadch commented 10 months ago

Overview

Add API to get just nullable Box instance without success flag and works faster.

API breakdown

namespace CommunityToolkit.HighPerformance;

public sealed class Box<T>
{
    /// <summary>
    /// Tries to get a nullable <see cref="Box{T}"/> reference from an input <see cref="object"/> representing a boxed <typeparamref name="T"/> value.
    /// </summary>
    /// <param name="obj">The input <see cref="object"/> instance to check.</param>
    /// <returns><see cref="Box{T}"/> instance if it was retrieved correctly, otherwise see langword="null"/>.</returns>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static Box<T>? TryGetFrom(object obj) => obj.GetType() == typeof(T) ? Unsafe.As<Box<T>>(obj)! : null;
}

Usage example

public class Some
{
    private Box<some>? box;

    public Some (object value)
    {
        box = Box<some>.TryGetFrom(value); // not Box<some>.TryGetFrom(value, out box);
    }
}

Breaking change?

No

Alternatives

I am not sure.

Additional context

No response

Help us help you

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

Sergio0694 commented 8 months ago

Closing this too, once again same reason as in https://github.com/CommunityToolkit/dotnet/issues/822#issuecomment-1902140162. Thank you!