I have two versions of helper methods for logging on ILogger. The first (classic extension methods) compiles fine; the second using extension members results in a compiler warning/error code.
CS8620: Argument of type ‘(string, object EntityPath)’ cannot be used for parameter ‘scopes’ of type ‘(string key, object? value)[]
Working version:
public static class LoggerExtensions
{
public static IDisposable? BeginKeyValueScope(this ILogger logger,
params (string key, object? value)[] scopes)
{
return logger.BeginScope(
new Dictionary<string, object?>(scopes.Select(x =>
new KeyValuePair<string, object?>(x.key, x.value))));
}
public static IDisposable? BeginAzureServiceBusReceptionScope(this ILogger logger, ProcessMessageEventArgs args)
{
return logger.BeginKeyValueScope(
("AzureServiceBusEntityPath", args.EntityPath),
("AzureServiceBusMessageId", args.Message.MessageId)
);
}
}
Failing version using extension‐members:
public static class LoggerExtensions
{
extension(ILogger logger)
{
public IDisposable? BeginKeyValueScope(params (string key, object? value)[] scopes)
{
return logger.BeginScope(
new Dictionary<string, object?>(scopes.Select(x =>
new KeyValuePair<string, object?>(x.key, x.value))));
}
public IDisposable? BeginAzureServiceBusReceptionScope(ProcessMessageEventArgs args)
{
return logger.BeginKeyValueScope(
("AzureServiceBusEntityPath", args.EntityPath),
("AzureServiceBusMessageId", args.Message.MessageId)
);
}
}
}
Why does the extension-members version trigger CS8620 while the classic version does not?
Is this a compiler limitation/bug (less likely) with the new extension‐members syntax or am I doing something wrong (much more likely).
x.valueis anobject, not anobject?. The code already had a problem. Post the full compiler error and look at the actual line the error points to. I suspect it'snew KeyValuePair<string, object?>(x.key, x.value)Post the full compiler error and look at the actual line the error points to.because I'm just guessing thatx.valuecould be involved, because that's the only place where I see the possibility of anobject. I'd have to invent code to reproduce any problems, and end up with ano-reproor the wrong problemsscopesparameter though, and that a value can't be used for it - which strongly suggests it's the call toBeginKeyValueScoperather than the call toBeginScopeorSelectthat's failing. But I certainly agree that the less that's left to the imagination/deduction, the better.