Skip to content

Commit

Permalink
S3655: Boxing (#6996)
Browse files Browse the repository at this point in the history
  • Loading branch information
antonioaversa authored and pavel-mikula-sonarsource committed Mar 31, 2023
1 parent 9be9ba3 commit d6211d9
Showing 1 changed file with 84 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,90 @@ async Task WithAsyncAwait()
}
}

class Boxing
{
void EmptyNullable()
{
int? nullable = null;
object implicitBoxed = nullable;
_ = (int)implicitBoxed; // Compliant, true null-dereference -> no nullable value access
var explicitBoxed = (object)nullable;
_ = (int)explicitBoxed; // Compliant
_ = (int)(object)(int?)(null); // Compliant
_ = (int)(object)(null as int?); // Compliant
}

void EmptyNullableRoundTrip()
{
int? nullable = null;
object implicitBoxed = nullable;
int? unboxedNullable = (int?)implicitBoxed;
_ = unboxedNullable.Value; // Noncompliant, empty
}

void NonEmptyNullableRoundTrip()
{
int? nullable = 42;
object implicitBoxed = nullable;
int? unboxedNullable = (int?)implicitBoxed;
_ = unboxedNullable.Value; // Compliant, non-empty
}

void UnknownNullableRoundTrip(int? nullable)
{
object implicitBoxed = nullable;
int? unboxedNullable = (int?)implicitBoxed;
_ = unboxedNullable.Value; // Compliant, unknown
}

void NonEmptyNullable()
{
int? nullable = 42;
object implicitBoxed = nullable;
_ = (int)implicitBoxed; // Compliant
var explicitBoxed = (object)nullable;
_ = (int)explicitBoxed; // Compliant
}

void ImplicitAndExplicitConversion()
{
int? intNullable = 42;
object boxedInt = intNullable;
_ = (short)intNullable; // Compliant, cast exception from int unboxing -> no nullable value access
}

void ForeachExplicitConversion()
{
foreach (int i in new int?[] { null, 42 }) { } // FN
foreach (int i in new long?[] { null, 42, 42L }) { } // FN
}

void ForeachImplictConversion()
{
foreach (object boxed in new int?[] { null, 42 })
{
_ = (int)boxed; // Compliant
}
}

void CollectionImplicitBoxing()
{
foreach (var boxed in new object[] { null as int? })
{
_ = (int)boxed; // Compliant
}
foreach (var boxed in new List<object> { null as int? })
{
_ = (int)boxed; // Compliant
}
foreach (var (boxed1, boxed2) in new Dictionary<object, object> { { 42 as int?, null as int? } })
{
_ = (int)boxed1; // Compliant
_ = (int)boxed2; // Compliant
}
}
}

namespace WithAliases
{
using MaybeInt = Nullable<System.Int32>;
Expand Down

0 comments on commit d6211d9

Please sign in to comment.