Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add 'TryGetConstructorArgument' extension
  • Loading branch information
Sergio0694 committed Nov 29, 2024
commit 1b51b6c8f8a7217a27d2febaded35542d1d013c0
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// more info in ThirdPartyNotices.txt in the root of the project.

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;

namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions;
Expand Down Expand Up @@ -53,6 +54,29 @@ properties.Value.Value is T argumentValue &&
return null;
}

/// <summary>
/// Tries to get a constructor argument at a given index from the input <see cref="AttributeData"/> instance.
/// </summary>
/// <typeparam name="T">The type of constructor argument to retrieve.</typeparam>
/// <param name="attributeData">The target <see cref="AttributeData"/> instance to get the argument from.</param>
/// <param name="index">The index of the argument to try to retrieve.</param>
/// <param name="result">The resulting argument, if it was found.</param>
/// <returns>Whether or not an argument of type <typeparamref name="T"/> at position <paramref name="index"/> was found.</returns>
public static bool TryGetConstructorArgument<T>(this AttributeData attributeData, int index, [NotNullWhen(true)] out T? result)
{
if (attributeData.ConstructorArguments.Length > index &&
attributeData.ConstructorArguments[index].Value is T argument)
{
result = argument;

return true;
}

result = default;

return false;
}

/// <summary>
/// Gets a given named argument value from an <see cref="AttributeData"/> instance, or a fallback value.
/// </summary>
Expand Down