Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Format descriptive text

Tags:

c#

Is it possible to add some descriptive text to a string format specifier?

Example:

  string.Format ("{0:ForeName} is not at home", person.ForeName); 

In the example ForeName is added as description.

The above syntax is obviously incorrect, but just to show the idea.

The reason I am asking, is because in my case the strings are in a resource file, so in the resource file you currently only see

   {0} is not at home

in some cases it is hard to grasp what the context of {0} is.

EDIT:

In c# 6 string interpolation with the $ operator has been introduced, so string.Format is not needed anymore:

$"{person.ForeName} is not at home";
like image 468
thumbmunkeys Avatar asked Jan 23 '14 14:01

thumbmunkeys


People also ask

What is a formatting string?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.

What is string format in JavaScript?

JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on.


2 Answers

We usually put comments into our resources file e.g. {0} = Forename.

Then anybody who might be translating the string knows what {0} represents and can translate accordingly.

Also if you use ReSharper, you can enter the comment at the same time when you are adding your string to resources.

like image 135
jandic Avatar answered Oct 11 '22 22:10

jandic


Phil Haack and Peli have written a couple of interesting blog posts about alternatives to the default string.format function. They might interest you.

Basically they allow you to use object properties inside the format string like this:

string s = NamedFormat("Hello {FullName} ({EmailAdrress})!", person);

You can the related blog posts here:

  • http://blog.dotnetwiki.org/2009/01/16/NamedFormatsPexTestimonium.aspx
  • http://haacked.com/archive/2009/01/14/named-formats-redux.aspx/
  • http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx/

Perhaps one of the solutions covered in those blog posts would suit your needs.

like image 23
artokai Avatar answered Oct 11 '22 22:10

artokai