views:

320

answers:

3

I'm trying to implement a C# method that can log a message with a format string and a variable number of printf-style arguments. Ideally, it would work identically to the C function I pasted below, although idiomatic to C# of course.

static
void
LogMessage(const char * iFormat, ...)
{
  va_list argp;
  FILE * fp;

  fp = fopen("log.txt", "a");
  if (fp != NULL) {
    va_start(argp, iFormat);
    vfprintf(fp, iFormat, argp);
    va_end(argp);
    fprintf(fp, "\n");
    fclose(fp);
  }
}

This function is convenient for me, as it allows me to make the following calls:

LogMessage("Testing");
LogMessage("Testing %s", "1 2 3");
LogMessage("Testing %d %d %d", 1, 2, 3);
+4  A: 
static void LogMessage(string format, params object[] args) {
    File.AppendAllText("log.txt", string.Format(format, args));
}

LogMessage("Testing {0} {1}", 1, "hi");
Jimmy
Thanks, this is exactly the type of thing I was looking for. I had some of the right elements, but just couldn't get them in the right "order"!
Emerick Rogul
A: 
static void LogMessage(params string [] logList)
{
    for ( int i = 0 ; i < logList.Length ; i++ )
       doLogging(logList[i]);
}
+2  A: 

You want to create a variadic function

C# uses the params keyword to do this

static void LogMessage(string formatString, params string[] formatArguments)
{
    string.Format(formatString, formatArguments);
}

Please note that the params keyword can only be used on the last parameter in the method signature and that it requires the parameter to be an array.

This is merely syntactic sugar for actually passing an array.

dss539