0. Origin:
The writing originated from the discussion of Ruan--FxCop told me to check whether a string is empty and to use string. Length. 》。 In fact, people who have used FxCop know that it will advise you to use the String.Length attribute to determine whether the string is empty, but do you understand why? Today a little idle, deliberately write down this article, hope a little help.
1. Three commonly used string null method:
Length method: bool IsEmpty = (str. Length = = 0);
Empty method: BOOL IsEmpty = (str = = String.Empty);
General law: BOOL IsEmpty = (str = = "");
2. Deep internal mechanisms:
To explore the internal mechanisms of these three approaches, we have to look first. NET is how to achieve, that is to see. NET's source code! However, where do we find the source code? We also have three ways:
Rotor method: A good choice is Microsoft's rotor, this is a Microsoft's source code sharing project.
Mono method: Another good choice of course is the real open source project Mono!
Reflector method: The last option is to use the reverse compiler, but the reorganization of the code is not necessarily the original, but is an "approximation", you can consider using the reflector of the counter compiler [1].
Here I use the reflector method, we first look at the source code [2] (fragment):
public sealed class string:icomparable, ICloneable, IConvertible, IEnumerable, Icomparable<string>,
{
static string ()
{
String. Empty = "";
//code here
}
//code here
public static readonly string Empty;
public static bool operator = = (String A, string b)
{
return string. Equals (A, b);
}
public static bool Equals (string A, string b)
{
if (a = = b)
{
Return t Rue
}
if ((a!= null) && (b!= null))
{
return string. Equalshelper (A, b);
}
return false;
}
Private static unsafe bool Equalshelper (string ao, string bo)
{
//Code here
Int n Um1 = ao. Length;
if (Num1!= bo. Length)
{
return false;
//Code here
}
private extern int internallength ();
Public int Length
{br> get
{
. Internallength ();
}
}
//Code here
}
The code in the rotor string class is no different than this, except that there is no Equalshelper method to replace it with the following declaration:
public extern bool Equals (String value);