Is there a way to make "destructive" string methods a-la Ruby?

In Ruby, methods that change an object have an end at the end: string.downcase!

In C #, you need to do: foo = foo.ToLower()

Is there a way to make an extension method like:

foo.ConvertToLower()

who will manipulate foo

?

(I think the answer is no, since strings are immutable and you cannot do ref this

in an extension method.)

0


source to share


3 answers


No, you cannot do this in an extension method. To reassign the value of a variable passed as a parameter, you need to pass it by reference using a parameter modifier ref

, which is not allowed for extension methods. Even if it were possible, there cannot be a variable to reassign, for example in "foo".ConvertToLower()

.



0


source


There are two ways to modify a string instance:

  • Reflection
  • Unsafe code


I would not recommend using any of these. Your fellow developers hate you forever - especially if this method is ever used to modify a string that is a literal ...

+3


source


You can of course write an extension method to reassign the string you are using. For example:

public static void ConvertToLower(this string s)
{
   s = s.ToLower();
}

      

This has nothing to do with strings being immutable.

-3


source







All Articles