A bit of an academic question, but I'm trying to understand the framework design on a deeper level.
So we have String.IsNullOrEmpty(MyString)
and we could write an extension method to enable myString.IsNullOrEmpty()
, though that's arguably not the greatest idea. See: Is extending String class with IsNullOrEmpty confusing?.
So my question is, why doesn't MS write this functionality as part of the .Net framework? Is there some performance consideration? And more generally, why would any method or property viewed as valuable enough to be built as accessible via the String object not be available as a member of any object of the string type?
C# | IsNullOrEmpty() Method In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.
The IsNullOrEmpty() method returns true if the input is null . IsNullOrEmpty() returns true if the input is an empty string. In C#, this is a zero length string ("").
The C# IsNullOrEmpty() method is used to check whether the specified string is null or an Empty string. It returns a boolean value either true or false.
The static method String.IsNullOrEmpty
was introduced in the .NET Framework version 2.0. Extension methods were introduced in the .NET Framework version 3.5 together with LINQ. Therefore Microsoft did not have this option when introducing IsNullOrEmpty
.
Of course, IsNullOrEmpty
cannot be an instance method of String
, since you cannot invoke a method on a reference which is null
. However, you can invoke an extension method on such a reference, since the extension method syntax is just syntactic sugar for a static method invocation.
Let's assume that IsNullOrEmpty
was an extension method. Then you could call it like this:
string s = null; bool result = s.IsNullOrEmpty();
In a comment, someone pretends that this call would throw a NullReferenceException
. The extension method would be declared like this:
public static class StringExtensions { public static bool IsNullOrEmpty(this string s) { return s == null || s.Length == 0; } }
... and be used like this ...
string s = null; bool result = s.IsNullOrEmpty();
... which is just syntactic sugar for ...
string s = null; bool result = StringExtensions.IsNullOrEmpty(s);
... and thus, would not throw an exception. Whether it is a good idea or not to do so is another question (see answer provided by usr below).
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