Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible define an extension operator method?

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.

like image 485
mjsr Avatar asked Apr 01 '11 20:04

mjsr


People also ask

Can we define extension method?

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 define extension method for static class?

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.

What keyword is used to define an extension method?

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.

What is the correct definition of extension method Mcq?

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.


1 Answers

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.

like image 198
Matt Greer Avatar answered Oct 21 '22 11:10

Matt Greer