Is there a way to make “destructive” string methods a-la Ruby?
-
05-07-2019 - |
Question
In Ruby, methods which change the object have a bang on the end: string.downcase!
In c# you have to do: foo = foo.ToLower()
Is there a way to make an extension method like:
foo.ConvertToLower()
that would manipulate foo
?
(I think the answer is no since strings are immutable and you can't do a ref this
in an extension method.)
Solution
No, you cannot do this in an extension method. To reassign the value of a variable passed in as a parameter you have to pass it by reference using the ref
parameter modifier, what is not allowed for extension methods.
Even if this would be possible, there might not be a variable to reassign, like in "foo".ConvertToLower()
.
OTHER TIPS
There are two ways of mutating a string instance:
- Reflection
- Unsafe code
I wouldn't recommend using either of them. Your fellow developers will hate you forever - particularly if the method is ever used to change a string which happens to be a literal...
You can certainly write an extension method to re-assign the string being operated on. For example:
public static void ConvertToLower(this string s)
{
s = s.ToLower();
}
This has nothing to do with the immutability of strings.