7

I am wondering if it is possible to add a new property as an extension property to the string class. What I'm looking for is something like this

string.Empty

I would like to make an extension, ex:

string.DisplayNone;

Can I add extension properties to the string C# class that I can call in a similar manner like when I do string.Empty?

  • 2
    No, you cannot add a static extension method because extension methods require an instance of an object – Chandu Jul 21 '11 at 21:49
  • *forget it*. jon says its impossible http://stackoverflow.com/questions/1676191/adding-an-extension-method-to-the-string-class-c/1676214#1676214 :) – naveen Jul 21 '11 at 21:55
  • @Cybernate: It's correct that you can't add a static extension method, but it's not because an extension method requires an instance. You only need a reference of the correct type, but the reference can be null. – Guffa Jul 21 '11 at 22:28
  • How does "something".DisplayNone make any sense? The user of your code will forever be mystified why "nothing".DisplayNone returns the exact same thing. Understand the difference between static and instance properties. – Hans Passant Jul 22 '11 at 00:15

3 Answers3

4

Yeah, you can do this.. however it will be an extension method, not a property.

public static class Extensions
{
    public static string DisplayNone(this string instance)
    {
        return "blah";
    }
}

Which would need to be used (however hacky) as "".DisplayNone(); as it will require an instance of a string to be created.

If you wanted to though, another slightly less hacky way would be to create a helper class..

public static StringHelper
{
    public static string DisplayNone()
    {
        return "blah";
    }
}
fatty
  • 2,453
  • 2
  • 25
  • 24
  • No, calling an extension method doesn't require an instance of the class. You only need a reference of the right type, but the reference can be null. – Guffa Jul 21 '11 at 22:24
4

You can only build extensions for objects...

something like that:

class Program
{
    static void Main(string[] args)
    {
        string x = "Hello World";
        x.DisplayNow();
    }
}

public static class StringExtension
{
    public static void DisplayNow(this string source)
    {
        Console.WriteLine(source);
    }
}

but i've never seen how u can extend a struct or a class which has never been initialized.

Smokefoot
  • 1,695
  • 2
  • 10
  • 13
0

You might be able to create your own value type. That mimics the type String with a "DisplayName" method.

However, I can't see why you need "DisplayName" on the type? It makes more sense on the sting instance. I.e. "Hello".DisplayName. See Smokefoot's answer to this question.

Casey Burns
  • 1,223
  • 12
  • 15