Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement MyMethod() with Format("blah {0}", someValue) signature like string.format

String.Format and StringBuilder (via the AppendFormat method) allow callers to pump values into a string they have prepared, e.g:

string temp = string.Format("Item {0} of {1}, Record Id: {2} started...",
  itemCounter.ToString(),
  totalItemsToProcess.ToString(),
  myRecord.RecordId);
MyMethod(temp);

But rather than build a string and pass that into "MyMethod()" I'd rather have an overload that people called like this:

MyMethod("Item {0} of {1}, Record Id: {2} started...",
  itemCounter.ToString(),
  totalItemsToProcess.ToString(),
  myRecord.RecordId);

How would you implement that? Is there something I can leverage or do I have to write a bunch of custom code?

like image 730
Adrian K Avatar asked Apr 28 '11 05:04

Adrian K


People also ask

What is the purpose of string formatting?

Overview. String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.


2 Answers

It's pretty trivial, but there are less trivial uses of params:

static string MyMethod( string format, params object[] paramList )
{
    return string.Format(format, paramList);
}
like image 131
Christo Avatar answered Sep 28 '22 03:09

Christo


How about params? http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

like image 21
CharithJ Avatar answered Sep 28 '22 04:09

CharithJ