CJ7
CJ7

Reputation: 23275

How to implement parameterised string?

My app needs to allow the user to input and save a generic parameterised string.

What is the best way to do this in .NET?

Currently I allow the user to input a string with pre-defined "parameters" into a textbox.

eg. "Hi %%Name%%, please pick up your order number %%Order%%."

This generic string is then stored and then populated with real data as and when needed. The population is done simply by a series of these type of statements:

Str1.Replace("%%Name%%", data.Name)
Str1.Replace("%%Order%%", data.Order)

Upvotes: 0

Views: 85

Answers (4)

M4N
M4N

Reputation: 96551

Depending on the complexity of your use-cases, you might want to use a templating library such as NVelocity, StringTemplate or similar.

With NVelocity, you could have a template like this:

"Hi $data.Name, please pick up your order number $data.Order."

Then you simply pass your template and the data object to the NVelocity enginge and let it replace the placeholders.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

What you have is "good enough"... you just need to remember to assign the result of the Replace() call back to the original:

Str1 = Str1.Replace("%%Name%%", data.Name)
Str1 = Str1.Replace("%%Order%%", data.Order)

You can get better performance by implementing this as a state machine, but the complexity involved is unlikely to justify it, and I likewise feel like a full-featured templating library is probably overkill here. YAGNI

If I were to recommend a different syntax, I might go with a leading @ sign or question mark to match common database parameter syntax. Or if you can put up with indexed parameters rather than named parameters, you can just use String.Format() as suggested in another answer.

Upvotes: 0

Joshua Dwire
Joshua Dwire

Reputation: 5443

There was a similar question elsewhere on Stack Overflow. Here is a modification of part of Dogget's answer at https://stackoverflow.com/a/4077118/1721527

Define a function like this:

public string Format(string input, object p)
{
    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(p))
    {
        input = input.Replace("%%" + prop.Name + "%%", (prop.GetValue(p) ?? "(null)").ToString());
        return input;
    }
}

Call it like this:

Format("test %%first%% and %%another%%", new { first = "something", another = "something else" })

Upvotes: 0

are you looking for format strings?

string str = String.Format("five = {0} hello {1}", 5, "World");

or alternatively

string base = "five = {0} hello {1}"
string str = String.Format(base, 5, "World");

Upvotes: 3

Related Questions