Merge into pattern confusion

I have the following code:

public static string GetDescription<T>(this T value) where T : Enum
{
    var enumAttributes = typeof(T).GetField(value.ToString())?.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (enumAttributes is DescriptionAttribute[] descriptionAttributes && descriptionAttributes.Length > 0)
        return descriptionAttributes[0].Description;

    return value.ToString();
}

when I run the resharper command line tool is says (about the if statement condition):

Merge into pattern

What does it actually want me to do? Cannot see anything possible.

 

3 comments
Comment actions Permalink

At a guess:

if (enumAttributes is { Length: > 0 })

 

1
Comment actions Permalink

Richard Deeming There is no change of variable name? Unless you are referring to the new variable "descriptionAttributes" created by casting the "enumAttributes" value? The code above is as written in my project and builds and runs fine. 

Thanks for your suggestion though, this is (essentially) what it wanted, I wasn't aware that you could do the below to be honest. So what it wanted was for that line to be changed to:

if (enumAttributes is DescriptionAttribute[] { Length: > 0 } descriptionAttributes)

It would  be nice if it could provide more information on what it wants, not sure the message was too helpful considering it will know the exact code it wants you to change it to.

Thanks

0
Comment actions Permalink

D'oh! I missed that part of the pattern.

Of course, the method can be simplified still further by using the generic GetCustomAttribute method:

public static string GetDescription<T>(this T value) where T : Enum
{
    string result = value.ToString();
    return typeof(T).GetField(result)?.GetCustomAttribute<DescriptionAttribute>() is {} descriptionAttribute
        ? descriptionAttribute.Description
        : result;
}
0

Please sign in to leave a comment.