Reputation: 7908
How to replace a method signature to accept parameterized strings without using param keywords. I have seen this functionality in Console.WriteLine(). e.g.
public void LogErrors(string message, params string[] parameters) { }
Scenario:
I have an error login function called
LogErrors(string message)
{
//some code to log errors
}
I am calling this function at different locations in the program in a way that the error messages are hardcoded. e.g.:
LogError("Line number " + lineNumber + " has some invalid text");
I am going to move these error messages to a resource file since I might change the language (localization) of the program later. In that case, how can I program to accept curly bracket bases parameterized strings? e.g.:
LogError("Line number {0} has some invalid text", lineNumber)
will be written as:
LogError(Resources.Error1000, lineNumber)
where Error1000 will be "Line number {0} has some invalid text"
Upvotes: 4
Views: 1230
Reputation: 62504
Basically use String.Format() method:
public void LogError(string format, params string[] errorMessages)
{
log.WriteError(String.Format(
CultureInfo.InvariantCulture,
format,
errorMessages));
}
Upvotes: 2
Reputation: 1500665
You probably want two methods:
public void LogErrors(string message, params string[] parameters)
{
LogErrors(string.Format(message, parameters));
}
public void LogErrors(string message)
{
// Use methods with *no* formatting
}
I wouldn't just use a single method with the params
, as then it'll try to apply formatting even if you don't have any parameters, which can make things harder when you want to use "{" and "}" within a simple message without any parameters.
Upvotes: 7
Reputation: 887449
Just call String.Format
in your function:
string output = String.Format(message, parameters);
Upvotes: 12