I'm cleaning up some old code that's repeatedly doing myString.ToCharArray().Length
; instead of myString.Length
.
Before I refactor ToCharArray()
out, are there any circumstances where doing so would result in different behavior?
No difference : have a look the method code with reflector : it will allocate a char[] based on the length of the string.
Both will definitely return the same length, representing the number of characters (char
s). There'll be one char per each index of the string (or array), and, then, the following could be worthy of mention:
The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.
From this you can also deduce that ToCharArray
, given that it is "A Unicode character array whose elements are the individual characters of this instance", that they behave the same.
I'm not sure what the not on NullReferenceException
is about, as both are susceptible to that, too.
result in different behavior?
Well, as others said, in both ways, result will be the number of char
, so, the answer is definitly NO!
But I want to add something different to this answer.
When I decompile String.ToCharArray()
method, it looks like:
public unsafe char[] ToCharArray()
{
int length = this.Length;
char[] chArray = new char[length];
if (length > 0)
{
fixed (char* smem = &this.m_firstChar)
fixed (char* dmem = chArray)
string.wstrcpyPtrAligned(dmem, smem, length);
}
return chArray;
}
ToCharArray
uses unsafe
code that manipulates pointers, along with the private wstrcpyPtrAligned
method in the base class library. It is normally faster than doing the same thing in managed code, which has to check array bounds.
It makes a complete pass over the string, so if you do not require that, filling character arrays manually may be faster.
Since ToCharArray()
method returns a char array, which you can modify in-place. This sometimes improves the performance of code.
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