Partially from a curious breaking things point of view and partially from a safeguarding against potential problems. Imagine what is the worst that can happen by calling the following (or something similar, but string.Empty
is a good examples):
typeof(String).GetField("Empty",
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.GetField
).SetValue(null, "foo" );
This would cause problems when there's code somewhere that does x = myClass.bar ?? string.Empty
.
Is there any way (akin to different app domains or similar) to protect against (or detect) someone changing values like String.Empty
or perhaps the SqlDateTime.MinValue
(or other similar readonly fields in .NET)?
As mentioned before, a string is empty if its length is equal to zero. We will be using the length() method, which returns the total number of characters in our string.
Empty will serve you better than using “”. In the cases where String. Empty will not work either because of the code evaluation OR because of the performance considerations, yes, use “” instead. But, do it because there is a supportable reason, not because you think it may produce faster code.
To test whether the value of a string is either null or String.
C++ String empty() Function returns a Boolean value either true or false.
You could define your own const
fields in your assembly like so:
internal const string Empty = "";
And then perform a check against String.Empty
, but it's pretty much a futile effort.
You'd have to perform a check everywhere you access String.Empty
and effectively replace it (since you'd check at the point of comparison, there's no point in actually using String.Empty
over your version anymore).
Since it's const
, the value couldn't be changed, which is good, but at the same time, if the value of String.Empty
does ever change (however unlikely), you'll have to make the change to your value, and then recompile everything that references that field.
Of course, you could make your version readonly
, but then you'd be vulnerable to having the value changed through reflection, and you're right back where you started.
Add to that the fact that if String.Empty
was changed, not only would comparisons against the field be affected, but I'd imagine a tremendous number of methods in the BCL would just not work properly; looking through Reflector, it would seem it's referenced a few hundred times in mscorlib (.NET 4.0) alone:
So that said, you could try and guarantee that the value wasn't changed, but it just isn't practical (it will be an eternal game of cat-and-mouse), chances are, from the perspective of your program, if the value of String.Empty
was changed, the world would end, and the program would die a horrible death fairly quickly almost as soon as it was changed.
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