Skip to content

NET-2382 Fix AD0001: Analyzer 'SonarAnalyzer.CSharp.Rules.VariableShadowsField' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'. #9758

Description

@Silop024

Description

Using the new C# 14 extension members, SonarAnalyzer throws an exception.

Only see the exception in Azure pipelines.

Reproducer

extension<TEnum>(TEnum @enum)
	where TEnum : struct, Enum
{
	public EnumWrapper<TEnum> Wrap() =>
		new(@enum);

	public string GetDisplayName()
	{
		MemberInfo? memberInfo = @enum.GetType().GetMember(@enum.ToString()).FirstOrDefault();
		if (memberInfo is not null)
		{
			DisplayAttribute? displayAttribute = memberInfo.GetCustomAttribute<DisplayAttribute>();
			if (displayAttribute is not null && !string.IsNullOrEmpty(displayAttribute.GetName()))
			{
				return displayAttribute.GetName()!;
			}
		}

		return @enum.ToString();
	}

	public IEnumerable<TEnum> GetFlags() =>
		GetValuesExceptDefault<TEnum>().Where(flag => @enum.HasFlag(flag));

	public int ToInt() =>
		Convert.ToInt32(@enum, CultureInfo.InvariantCulture);
}

extension<TEnum>(TEnum)
	where TEnum : struct, Enum
{
	public static IEnumerable<EnumWrapper<TEnum>> GetWrappedValues() =>
		Enum.GetValues<TEnum>().Wrap();

	public static IEnumerable<TEnum> GetValuesExceptDefault() =>
		Enum.GetValues<TEnum>().Where(e => !Equals(e, default(TEnum)));
}

extension<TEnum>(IEnumerable<TEnum> enums)
	where TEnum : struct, Enum
{
	public IEnumerable<EnumWrapper<TEnum>> Wrap() =>
		enums.Select(Wrap);

	public TEnum CombineFlags()
	{
		var result = 0;

		foreach (TEnum enumValue in enums)
			result |= Convert.ToInt32(enumValue, CultureInfo.InvariantCulture);

		return (TEnum)Enum.ToObject(typeof(TEnum), result);
	}
}

Product and Version

NuGet version 10.15.0.120848

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugExceptions and blocking issues during analysis.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions