Sergio0694 / PolySharp

PolySharp provides generated, source-only polyfills for C# language features, to easily use all runtime-agnostic features downlevel. Add a reference, set your C# version to latest and have fun! 🚀
MIT License
1.83k stars 49 forks source link

What's the purpose of adding `TypeForwardedTo` attributes? #90

Open 0xced opened 1 year ago

0xced commented 1 year ago

In #86 you said

generate type forwards to ensure things work as expected in multi-targeting scenarios

Could you please elaborate a little bit more on this? What exact problem does it solve to add TypeForwardedTo attributes in target frameworks where the type exists?

For example, when multi-targeting net7.0;net6.0;netstandard2.0 the source generator produces this for .NET 6 and .NET 7 targets:

[assembly: global::System.Runtime.CompilerServices.TypeForwardedTo(typeof(global::System.Runtime.CompilerServices.IsExternalInit))]

If I add <PolySharpExcludeTypeForwardedToDeclarations>true</PolySharpExcludeTypeForwardedToDeclarations> they are not generated and everything seems to work fine. Am I missing something?

OwnageIsMagic commented 1 year ago

In case you generate attributes as public in lib A and have reference to them in another lib B (or generate as internal and use reflection). With this attribute lib A will always have definition of IsExternalInitAttribute (real or forwarded). Without it, there is a possibility of TypeLoadException in some edge cases if A and B are updated separately, but I wold say in any sane deploy scheme this should not be a problem. Or maybe I missing something obvious.

OwnageIsMagic commented 1 year ago

Like if you publish lib A ver 1, but in ver 2 change PolySharp settings, so this type is no longer generated. Lib B is transitive dep of app have dependency on A.v1, and app have direct dep on lib A.v2 -- assembly redirection would kick in and choose A.v2 and lib B will throw TypeLoadException.

WeihanLi commented 2 months ago

Find a document about the type forwarding, hope it helps https://learn.microsoft.com/en-us/dotnet/standard/assembly/type-forwarding