Record a message with a variable number of arguments printf-style

I am trying to implement a C # method that can log a message with a format string and a variable number of arguments of type printf. Ideally, it will work identically with the function C, which I inserted below, although, of course, idiomatically for C #.

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 because it allows me to make the following calls:

 LogMessage("Testing"); LogMessage("Testing %s", "1 2 3"); LogMessage("Testing %d %d %d", 1, 2, 3); 
+6
c # logging variadic-functions
source share
3 answers
 static void LogMessage(string format, params object[] args) { File.AppendAllText("log.txt", string.Format(format, args)); } LogMessage("Testing {0} {1}", 1, "hi"); 
+15
source share

You want to create a variational function

C # uses the params keyword to do this

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

Note that the params keyword can only be used in the last parameter in the method signature, and this requires this parameter to be an array .

It is just syntactic sugar for the actual passage of the array.

+9
source share
 static void LogMessage(params string [] logList) { for ( int i = 0 ; i < logList.Length ; i++ ) doLogging(logList[i]); } 
0
source share

All Articles