2

Is it possible to make the following example work with SmartFormat.NET?

void Main()
{
    Dictionary<string,string> ps = new Dictionary<string, string>();

    ps["Name"] = "Niels";

    Smart.Format("{Name.Foo} is my name", ps).Dump();   
}


public static class Extensions
{

    public static string Foo(this string bar)
    {
        return bar.ToUpper();
    }

}

This will return " is my name" in LinqPad. I want it to return "NIELS is my name". I'm using ToUpper only as a simple example.

Niels Bosma
  • 11,758
  • 29
  • 89
  • 148

2 Answers2

5

Short answer

It is currently not possible to call extension methods inside SmartFormat formatting braces.

To provide such a feature, SmartFormat would have to look for an extension method of string in all the assemblies of your project, as described in this thread.

Example review

  • Inside the formatting string

As specified in the project documentation, you can use the ToUpper() method directly inside the format braces, like this (as the method does not take any parameter):

Smart.Format("{Name.ToUpper} is my name", ps).Dump();

Maybe the SmartFormat developers should introduce Upper/Lowercase Format Specifiers in the future, as many people are looking for such things. Nevertheless, it would be quite a challenge for them as ToUpper() and ToLower() calls always seems to be faster than any other implementation or syntactic sugar.

  • Outside the formatting string

Another way to do it would be to call the extension method outside of your formatting string, but then you lose the Reflection Syntax advantages...

Smart.Format("{0} is my name", ps["Name"].Foo()).Dump();
Community
  • 1
  • 1
kamino
  • 395
  • 2
  • 11
0

No it will return is my name, can't call extensions method in SmartFormart.NET

oussama abdou
  • 317
  • 1
  • 7