Add new property to C # string class

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

string.Empty 

I would like to make an extension, for example:

 string.DisplayNone; 

Is it possible to add extension properties to a C # class, which I can call in a similar way, for example, when I do string.Empty?

+6
source share
3 answers

You can create 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 have never seen how you can extend a structure or class that has never been initialized.

+4
source

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

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

What will need to be used (as if hacked) as "".DisplayNone(); because this will require an instance of the string to be created.

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

 public static StringHelper { public static string DisplayNone() { return "blah"; } } 
+4
source

You may be able to create your own value type. This mimics the String type using the DisplayName method.

However, I do not understand why you need a "DisplayName" in the type? This is more important for instance sting. That is, Hello .DisplayName. See Smokefoot answer to this question.

0
source

Source: https://habr.com/ru/post/893317/


All Articles