Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Analyzer 'Roslynator.CSharp.Analysis.UseEnumFieldExplicitlyAnalyzer' threw an exception of type 'System.InvalidCastException' with message 'Unable to cast object of type 'System.Int32' to type 'System.SByte' #1262

Closed
jroessel opened this issue Nov 21, 2023 · 0 comments · Fixed by #1264
Assignees

Comments

@jroessel
Copy link
Contributor

jroessel commented Nov 21, 2023

Product and Version Used:

  • Visual Studio 2022 v17.7.7
  • Roslynator 4.6.2

Steps to Reproduce: Have an enum that derives from sbyte (other types may exhibit this problem as well), e.g. the following code, and have a cast of a numeric constant to that enum type somewhere.

var enumValue = TestEnum.Bar;
if (enumValue <= 0 || enumValue >= (TestEnum) 2)
{
  throw new Exception();
}

enum TestEnum : sbyte
{
  Foo, Bar, Baz
}

Actual Behavior:

Analyzer 'Roslynator.CSharp.Analysis.UseEnumFieldExplicitlyAnalyzer' threw an exception of type 'System.InvalidCastException' with message 'Unable to cast object of type 'System.Int32' to type 'System.SByte'.'.
Exception occurred with following context:
Compilation: ConsoleApp5
SyntaxTree: C:\Users\roessel\source\repos\ConsoleApp5\Program.cs
SyntaxNode: (TestEnum) 2 [CastExpressionSyntax]@[66..78) (1,35)-(1,47)

System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.SByte'.
   at Roslynator.ConvertHelpers.ConvertToUInt64(Object value, SpecialType numericType)
   at Roslynator.CSharp.Analysis.UseEnumFieldExplicitlyAnalyzer.AnalyzeCastExpression(SyntaxNodeAnalysisContext context)
   at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__49`1.<ExecuteSyntaxNodeAction>b__49_0(ValueTuple`2 data)
   at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info, CancellationToken cancellationToken)

Expected Behavior:

A suggestion to use the actual enum constant instead of the analyzer crashing.

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

Successfully merging a pull request may close this issue.

2 participants