I want to pass a params object from my method to another methods params object like the following, but I cannot figure out the syntax, or if it is even possible.
readonly ILogger<T> _logger;
readonly string _businessUnit = "Marketing";
private void LogTheThing(string message, params object?[] args) {
_logger.LogInformation($"{{BusinessUnit}} - {message}", _businessUnit, args);
}
public void Go() {
LogTheThing($"{{OrderId}} - Could not locate your order. Try searching for {{ExternalOrderId}}", 45623, "A987BZ1");
}
Currently when I pass LogTheThing‘s args to the ILogger‘s args, the array of objects from my method winds up in the first array element of the Ilogger‘s args.
I tried these with no luck:
_logger.LogInformation($"{{BusinessUnit}} - {message}", _businessUnit, args.ToArray()); // nope
_logger.LogInformation($"{{BusinessUnit}} - {message}", _businessUnit, args.ToList()); // nope
This example actually shows the unwanted – default behavior.
Is it possible to "spread" my args and have c# treat it as:
_logger.LogInformation($"{{BusinessUnit}} - {message}", _businessUnit, args[0], args[1], arg[x]...);
>Solution :
Basically you’d need to create an array containing both _businessUnit and all the args contents:
object[] newArgs = new object[args.Length + 1];
newArgs[0] = _businessUnit;
Array.Copy(args, 0, newArgs, 1, args.Length);
_logger.LogInformation($"{{BusinessUnit}} - {message}", newArgs);
There’s nothing built into C# as a language to do that.