Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing variable params to another variable params

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading