views:

383

answers:

4

Not sure what I'm doing wrong here. The extension method is not recognized.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            RunTests();
        }

        static void RunTests()
        {
            try
            {
                ///SafeFormat
                SafeFormat("Hi There");

                SafeFormat("test {0}", "value");

                SafeFormat("test missing second value {0} - {1}", "test1");

                SafeFormat("{0}");

                //regular format
                RegularFormat("Hi There");

                RegularFormat("test {0}", "value");

                RegularFormat("test missing second value {0} - {1}", "test1");

                RegularFormat("{0}");

                ///Fails to recognize the extension method here
                string.SafeFormat("Hello");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

        private static void RegularFormat(string fmt, params object[] args)
        {
            Console.WriteLine(String.Format(fmt, args));
        }

        private static void SafeFormat(string fmt, params object[] args)
        {
            string errorString = fmt;

            try
            {
                errorString = String.Format(fmt, args);
            }
            catch (System.FormatException) { } //logging string arguments were not correct
            Console.WriteLine(errorString);
        }

    }

}

namespace StringExtensions
{
    public static class StringExtensionsClass
    {
        public static string SafeFormat(this string s, string fmt, params object[] args)
        {
            string formattedString = fmt;

            try
            {
                formattedString = String.Format(fmt, args);
            }
            catch (System.FormatException) { } //logging string arguments were not correct
            return formattedString;
        }
    }
}
+2  A: 

try

"Hello".SafeFormat("{0} {1}", "two", "words")
Marek Karbarz
Brilliant. Wonder why it wasn't doing that for string.SafeFormat() ?
Chris Ballance
It doesn't have a reference to a string.
Daniel A. White
@Chris: Because string is the name of the type, not an instance of the type. Note that this example won't actually work, because the SafeFormat method requires two string arguments as well as the parameters.
Jon Skeet
I was thinking about the correct way this method needs to be called (on an instance rather than type) and neglected the arguments
Marek Karbarz
+10  A: 

You're trying to call it on the type string. You need to call it on a string instance, e.g.

"{0}".SafeFormat("Hello");

Admittedly that won't do what you want it to, because the SafeFormat method is actually completely ignoring the first parameter (s) anyway. It should look like this:

    public static string SafeFormat(this string fmt, params object[] args)
    {
        string formattedString = fmt;

        try
        {
            formattedString = String.Format(fmt, args);
        }
        catch (FormatException) {} //logging string arguments were not correct
        return formattedString;
    }

Then you can call:

"{0} {1}".SafeFormat("Hi", "there");

The point of extension methods is that they look like instance methods on the extended type. You can't create extension methods which appear to be static methods on the extended type.

Jon Skeet
Jon, should we call you Tony from now on, or did you change your nick just for fun? :) I am just asking because me not being here for a week or so, I missed some stuff it seems.
Joan Venge
Keep calling me Jon. It's just a reference to my DevDays talk. I'll change it back in about a week.
Jon Skeet
Hehe, ok Jon. Thanks for your explanation :)
Joan Venge
+5  A: 

You're defining an instance extension method, and then trying to use it as a static method. (C# is not capable of defining a static extension method, though F# is for that matter.)

Instead of:

result = string.SafeFormat("Hello");

you want something like:

result = "Hello".SafeFormat();

i.e. You're operating on the string instance ("Hello" in this case).

Noldorin
+1  A: 

Extension methods appear on instances of a type, not the type itself (e.g. static members).

Rex M