Raheel Khan
Raheel Khan

Reputation: 14787

Warning about unsafe for trimming and AOT compatibility if passed across the WinRT ABI (List<T>)

I have a simple .NET 8 (C#) class library that reads some registry values.

It was created and built in Visual Sudio 2022 (64 Bit) v17.11.5.

PROJECT FILE:

<PropertyGroup>
    <TargetFramework>net8.0-windows10.0.26100.0</TargetFramework>
    <ImplicitUsings>disable</ImplicitUsings>
    <Nullable>enable</Nullable>
</PropertyGroup>

METHODS:

public static RegistryKey? GetRegistryKey () =>
    Registry
        .CurrentUser
        .OpenSubKey("Software")
        ?.OpenSubKey("ODBC")
        ?.OpenSubKey("ODBC.INI")
        ?.OpenSubKey("ODBC Data Sources");

public static IEnumerable<string> GetDataSources1 ()
{
    using var key = DataProviderOdbc.GetRegistryKey();
    {
        // Only the following line causes the warning (listed below).
        return (key?.GetValueNames()?.ToList() ?? []);
    }
}

public static string [] GetDataSources2 (RegistryKey? key)
    => key?.GetValueNames() ?? [];

public static IEnumerable<string> GetDataSources3 (RegistryKey? key)
    => key?.GetValueNames()?.ToList() ?? [];

public static IEnumerable<string> GetDataSources4 ()
    => DataProviderOdbc.GetRegistryKey()?.GetValueNames()?.ToList() ?? [];

Code: CsWinRT1030
Type 'System.Collections.Generic.List<string>' implements generic WinRT interfaces which requires generated code using unsafe for trimming and AOT compatibility if passed across the WinRT ABI. Project needs to be updated with '<AllowUnsafeBlocks>true</AllowUnsafeBlocks>'.

I do not understand why only the first implementation named GetDataSources1 results in the above warning. At first, I thought this was a consolidated warning so I tried re-ordering and commenting the methods in all combinations. I cleaned and rebuilt the solution in vain.

The library is full of both, implicit and explicit casts between T[], IEnumerable, LIST, etc. Why only that line? I must be doing something stupid. What am I missing? Why would I/should I consider marking the assembly to allow unsafe code?

Side question: Does this even have anything to do with the registry at all (I am assuming not)? I don't know much about the WinRT bridge and why is even being considered here at all. Any insight into the meaning of this warning would be appreciated as well.

UPDATE: The error goes away when I change the line:

return (key?.GetValueNames()?.ToList() ?? []);

to

return (key?.GetValueNames()?.AsEnumerable() ?? []);

Upvotes: 6

Views: 1008

Answers (0)

Related Questions