19

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";
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • 2
    You want the dev who is reading the code to know what is going in `{0}`, that's it? A kind of comment? – Johnny5 Jan 23 '14 at 14:52
  • 1
    What's the intent here? – crush Jan 23 '14 at 14:52
  • 7
    Just google "string format named parameters". There's no native way to do it, only workarounds. http://stackoverflow.com/questions/159017/named-string-formatting-in-c-sharp – Dmitriy Khaykin Jan 23 '14 at 14:52
  • @crush: It sounds like the intent is to use intuitive naming on larger format strings, making the code more readable. Essentially treating the format string placeholders as variables (similar to SQL parameter placeholders). – David Jan 23 '14 at 14:54
  • 2
    Perhaps you could use [Mustache for .NET (Nustache)](https://github.com/jdiamond/Nustache). It's available on NuGet. I've never used it in .NET, though. It might be overkill. – crush Jan 23 '14 at 14:55
  • thanks for all the suggestions! Apparently it is not possible out of the box... I will give a try to the suggestion of @DavidKhaykin – thumbmunkeys Jan 23 '14 at 14:57
  • Is the `:ForeName` just a note? Or should it somehow tell the formatter which parameter to select? – crush Jan 23 '14 at 15:08
  • @crush it is like a comment, that describes what {0} stands for – thumbmunkeys Jan 23 '14 at 15:09
  • Duplicate? http://stackoverflow.com/questions/159017/named-string-formatting-in-c-sharp – WernerCD Jan 24 '14 at 00:33

7 Answers7

14

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.

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
jandic
  • 195
  • 4
14

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:

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

artokai
  • 405
  • 3
  • 8
7

For strings your method should work, since strings will ignore any format specifiers. However you run the risk of accidentally using that for non-string types, in which case the string will either be translated as format codes or literally displayed:

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

string.Format ("{0:ForeName} will be home at {1:HomeTime}", "Johnny", DateTime.Today)
//Johnny will be home at 0o0eTi0e  -- H, h, and m are DateTime format codes.

However since you're storing these in a resource file, I would instead use the "comment" field in the resource file - you could store a copy of the format string and add your descriptions there.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
4

There is no built-in C# function for that. The best I can propose is to insert a comment (this will have no performance impact) :

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

Personnaly, I don't find it readable, the best approch is to use a third-party tool as David Khaykin suggested in comment (see this answer)

Community
  • 1
  • 1
AlexH
  • 2,650
  • 1
  • 27
  • 35
  • thanks, but the point is that the description should be in the string, so it gets into the resource file – thumbmunkeys Jan 23 '14 at 14:59
  • I like the "No performance impact" part of this. But the author is talking if resources file. Can we put comments in resources files? – Johnny5 Jan 23 '14 at 14:59
  • @Johnny5 it is possible to add a comment to resx file entries, so that is a viable option to just comment it in there – thumbmunkeys Jan 23 '14 at 15:02
  • When I replied, the resx contraint wasn't mentioned. I think Jandic gave the best answer – AlexH Jan 23 '14 at 15:15
4

IDEOne.com demo

Here is a somewhat naive implementation of StackOverflow's formatUnicorn method:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Reflection;

public class Test
{
    public static void Main()
    {
        string formatString = "{firstName} {lastName} is awesome.";

        Console.WriteLine(formatString.FormatUnicorn(new {
            firstName = "joe",
            lastName = "blow"
        }));
    }
}

public static class StringExtensions {
    public static string FormatUnicorn(this string str, object arguments) {
        string output = str;

        Type type = arguments.GetType();

        foreach (PropertyInfo property in type.GetProperties())
        {
            Regex regex = new Regex(@"\{" + property.Name + @"\}");
            output = regex.Replace(output, property.GetValue(arguments, null).ToString());
        }

        return output;
    }
}

The biggest drawback here is the use of reflection, which can be slow. The other is that it doesn't allow for format specifiers.

A better approach might be to create a more complex regular expression that just strips out the comments.

crush
  • 16,713
  • 9
  • 59
  • 100
1
 string.Format ("{0} is not at home {1} ", person.ForeName, person.Something); 

This shall print the ForeName instead of {0} and something in {1}. There is no way to as you said.

Rajesh Subramanian
  • 6,400
  • 5
  • 29
  • 42
0

As of Visual Studio 2015 you can do this with Interpolated Strings (its a compiler trick, so it doesn't matter which version of the .net framework you target).

The code then looks something like this

string txt = $"{person.ForeName} is not at home {person.Something}"; 

Its not ideal if you want to put the strings into resource files for translation, but it oftern makes the code more readable and less error prone.

Sprotty
  • 5,676
  • 3
  • 33
  • 52