Skip to content

Commit

Permalink
Fix #2808: Insert cast to object when statically casting from dynamic…
Browse files Browse the repository at this point in the history
… to a reference type.
  • Loading branch information
siegfriedpammer committed Oct 21, 2022
1 parent e0c5b20 commit 42668e8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
24 changes: 24 additions & 0 deletions ICSharpCode.Decompiler.Tests/TestCases/Pretty/DynamicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ public void Method(dynamic a)
}
}

public interface I
{
}

private static dynamic field;
private static object objectField;
public dynamic Property { get; set; }
Expand Down Expand Up @@ -492,6 +496,26 @@ private static int ExplicitCast(object o)
return (int)(dynamic)o;
}

private static dynamic GetI()
{
return null;
}

public I Test()
{
return GetI();
}

public I Test1()
{
return (I)GetI();
}

public I Test2()
{
return (I)(object)GetI();
}

#if CS72
public void RefParams(ref object a, ref dynamic b, ref dynamic c)
{
Expand Down
11 changes: 11 additions & 0 deletions ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,17 @@ public TranslatedExpression ConvertTo(IType targetType, ExpressionBuilder expres
.ConvertTo(targetType, expressionBuilder, checkForOverflow, allowImplicitConversion);
}
}
else if (type.Kind == TypeKind.Dynamic && targetType.IsReferenceType == true && !targetType.IsKnownType(KnownTypeCode.Object))
{
// "static" conversion between dynamic and a reference type requires us to add a cast to object,
// otherwise recompilation would produce a dynamic cast.
// (T)dynamicExpression is a "dynamic" cast
// (T)(object)dynamicExpression is a "static" cast
// as "dynamic" casts are handled differently by ExpressionBuilder.VisitDynamicConvertInstruction
// we can always insert the cast to object, if we encounter a conversion from any reference type to dynamic.
return this.ConvertTo(compilation.FindType(KnownTypeCode.Object), expressionBuilder)
.ConvertTo(targetType, expressionBuilder, checkForOverflow, allowImplicitConversion);
}
if (targetType.Kind.IsAnyPointer() && (0.Equals(ResolveResult.ConstantValue) || 0u.Equals(ResolveResult.ConstantValue)))
{
if (allowImplicitConversion)
Expand Down

0 comments on commit 42668e8

Please sign in to comment.