String Parameterization in .NET C #

How to replace a method signature for accepting parameterized strings without using parameter keywords. I saw this function in Console.WriteLine (). eg

public void LogErrors(string message, params string[] parameters) { } 

Scenario:

I have a login function called

 LogErrors(string message) { //some code to log errors } 

I call this function in different places in the program so that the error messages are hard-coded. eg:.

 LogError("Line number " + lineNumber + " has some invalid text"); 

I am going to move these error messages to a resource file, since later I can change the language (localization) of the program. In this case, how can I program to insert curly braces with parameterized strings? eg:.

 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"

+4
source share
3 answers

You probably need 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 would not use only one method with params , since then it will try to apply formatting even if you do not have parameters, which can complicate the work if you want to use "{and"} "in a simple message without any parameters.

+7
source

Just call String.Format in your function:

 string output = String.Format(message, parameters); 
+12
source

Basically use the String.Format () method :

 public void LogError(string format, params string[] errorMessages) { log.WriteError(String.Format( CultureInfo.InvariantCulture, format, errorMessages)); } 
+2
source

All Articles