Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parametrizing string in .NET C#

Tags:

string

c#

.net

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"

like image 484
Sriwantha Attanayake Avatar asked Nov 30 '22 16:11

Sriwantha Attanayake


1 Answers

Just call String.Format in your function:

string output = String.Format(message, parameters);
like image 58
SLaks Avatar answered Dec 08 '22 00:12

SLaks