Skip to content

Commit 1b51b6c

Browse files
committed
Add 'TryGetConstructorArgument' extension
1 parent e094757 commit 1b51b6c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/CommunityToolkit.Mvvm.SourceGenerators/Extensions/AttributeDataExtensions.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
// more info in ThirdPartyNotices.txt in the root of the project.
77

88
using System.Collections.Generic;
9+
using System.Diagnostics.CodeAnalysis;
910
using Microsoft.CodeAnalysis;
1011

1112
namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions;
@@ -53,6 +54,29 @@ properties.Value.Value is T argumentValue &&
5354
return null;
5455
}
5556

57+
/// <summary>
58+
/// Tries to get a constructor argument at a given index from the input <see cref="AttributeData"/> instance.
59+
/// </summary>
60+
/// <typeparam name="T">The type of constructor argument to retrieve.</typeparam>
61+
/// <param name="attributeData">The target <see cref="AttributeData"/> instance to get the argument from.</param>
62+
/// <param name="index">The index of the argument to try to retrieve.</param>
63+
/// <param name="result">The resulting argument, if it was found.</param>
64+
/// <returns>Whether or not an argument of type <typeparamref name="T"/> at position <paramref name="index"/> was found.</returns>
65+
public static bool TryGetConstructorArgument<T>(this AttributeData attributeData, int index, [NotNullWhen(true)] out T? result)
66+
{
67+
if (attributeData.ConstructorArguments.Length > index &&
68+
attributeData.ConstructorArguments[index].Value is T argument)
69+
{
70+
result = argument;
71+
72+
return true;
73+
}
74+
75+
result = default;
76+
77+
return false;
78+
}
79+
5680
/// <summary>
5781
/// Gets a given named argument value from an <see cref="AttributeData"/> instance, or a fallback value.
5882
/// </summary>

0 commit comments

Comments
 (0)