Roland
Roland

Reputation: 5234

C# passing function with variable argument list as an argument

I am trying to hide complexities in functions to make for easy function calls. For example a function Log(string msg) for writing text messages to a textbox control, with a newline, and Invoke() for multi-threading. Now I want to avoid having to use Log(string.Format("..{0}..", x, ...)) and wrote a version of Log(string format, params object[] args), which works great.

Until I need to pass this Log() as an argument to another function that needs to do logging:

AnotherFunction(Action<string, object[]> Log)
{
  Log("formatstring", new object[] { value1, value2, ...});
}

My question: how can I avoid having to code the new object[] construction each time I have to call Log()?

Upvotes: 1

Views: 2193

Answers (2)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

I agree that an interface would be the cleanest solution. If that isn't an option however, you can always create your own delegate that uses params:

public delegate void FormattingLoggerDelegate(string format,
                                              params object[] args);

AnotherFunction would look like this:

public void AnotherFunction(FormattingLoggerDelegate log)
{
    log("formatstring", value1, value2);
}

Usage would be transparent, i.e. no need to cast to your delegate. Just like with Action an implicit cast exists:

AnotherFunction(Log);

Demo

Upvotes: 4

devdigital
devdigital

Reputation: 34349

An interface would be cleaner. You might also want to consider using an existing logging framework (such as log4net or NLog), and implement a target (or use an existing one) that writes output to a textbox.

Upvotes: 1

Related Questions