Skip to content

IDE wrongly reports "Cast is Redundant" for an implicit conversion #36782

@skybound

Description

@skybound

Version Used:
Visual Studio 2019 Preview 19.3, C# 7.3 (also tried 8.0 beta)

Steps to Reproduce:

using System;

namespace WrongRedundantCastWarning
{
	struct Flag
	{
		public Flag(int value) => this.Value = value;

		public int Value { get; }

		// This cast is wrongly reported as redundant
		public static FlagSet operator ~(Flag flag) => ~(FlagSet)flag;
	}

	struct FlagSet
	{
		public FlagSet(int value) => this.Value = value;

		public int Value { get; }

		public static implicit operator FlagSet(Flag flag) => new FlagSet(flag.Value);

		public static FlagSet operator ~(FlagSet flagSet) => new FlagSet(~flagSet.Value);
	}

	class Program
	{
		static readonly Flag One = new Flag(1);
		static readonly Flag Two = new Flag(2);

		static void Main(string[] args)
		{
			var flipped = ~Two;

			Console.WriteLine(flipped.Value);
		}
	}
}

The example has two types (Flag and FlagSet), with an implicit conversion defined from Flag to FlagSet.

Both types define the bitwise complement operator (~).

The implementation of Flag's bitwise complement operator invokes the implementation in FlagSet by casting itself to a FlagSet. This cast is not redundant -- without it, no conversion takes place, and the operator just calls itself leading to StackOverflowException.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-IDEBugIDE-CodeStyleBuilt-in analyzers, fixes, and refactoringshelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions