Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an extension method to the string class - C#

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;
        }
    }
}
like image 251
Chris Ballance Avatar asked Nov 04 '09 19:11

Chris Ballance


People also ask

Can you add extension method to an existing static class in C#?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.

Can you add extension method to an existing static class?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Can we extend string class in C#?

Yes, you can extend existing types by using extension methods. Extension methods, naturally, can only access the public interface of the type.


2 Answers

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.

like image 107
Jon Skeet Avatar answered Oct 06 '22 02:10

Jon Skeet


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).

like image 26
Noldorin Avatar answered Oct 06 '22 03:10

Noldorin