is it possible to define an extension method that at the same time is an operator? I want for a fixed class add the possibility to use a known operator that actually can't be applied. For this particular case i want to do this:
somestring++; //i really know that this string contains a numeric value
And i don't want to spread types conversions for all the code. I know that i could create wrapper class over an string and define that operator but i want to know if this kind of thing is possible to avoid search-and-replace every string declaration with MySpecialString.
Edited: as most have say string is sealed, so derivation isn't possible, so i modify "derived" to "wrapper", my mistake.
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.
No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
Extension Method uses the "this" keyword as the first parameter. The first parameter always specifies the type that the method operates on. The extension method is written inside a static class and the method is also defined as static.
are a special kind of static method. provide a way to add methods to existing types without modifying them. provide a way to add methods to existing types without new derived type.
That is not possible in C#, but why not a standard extension method?
public static class StringExtensions {
public static string Increment(this string s) {
....
}
}
I think somestring.Increment()
is even more readable, as you're not confusing people who really dont expect to see ++
applied to a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With