0

Is it possible to add an additional static method to .Net string class so I could write:

var header = string.FormatHeader(str1,str2,str3,formatOption);
juharr
  • 31,741
  • 4
  • 58
  • 93
ehh
  • 3,412
  • 7
  • 43
  • 91
  • 2
    Since it isn't quite clear: If you mean "can I add a method that behaves like a static method of the `string` class", then no. If you want a method that behaves like an instance method, then see Arkadiusz K's answer. – Glorin Oakenfoot Mar 17 '16 at 13:34
  • I meant to the static method of the string class – ehh Mar 17 '16 at 13:36
  • 2
    Does http://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class answer your problem? – Andy Mar 17 '16 at 13:49
  • Yes @Andy, it answers. Thank you – ehh Mar 17 '16 at 13:51

3 Answers3

2

TLDR:

No.

Bit more:

Extension methods must recieve an instance to work on:

void static  Foo(this string s)
{
    // Do something
}

There is no syntax for just off the string.

BanksySan
  • 27,362
  • 33
  • 117
  • 216
1

No, you can't add new static methods to the string class. You'd be better off writing your own StringUtils class or HeaderUtils class or something if there's no logical class for it to be a member of.

Richard Irons
  • 1,433
  • 8
  • 16
1

No it's not possible, extension methods are just syntactic sugar. It will be converted by the compiler to something like StringExtensions.FormatHeader(..);. The best you can do here is to create something like a helper class to handle this for you.

public class StringHelper
{
    public static string FormatHeader(string str1, string str2, string str3, FormatOption formatOption)
    {
        throw new NotImplementedException();
    }
}
Simon Karlsson
  • 4,090
  • 22
  • 39