Why is String.IsNullOrEmpty (str) and not str.IsNullOrEmpty ()?

Possible duplicate:
string.IsNullOrEmpty () vs string.NotNullOrEmpty ()

Can someone explain to me why in .NET I would write String.IsNullOrEmpty(str) instead of str.IsNullOrEmpty() ? There must be a logical reason, but I don't know that.

It looks like you guys are talking

  • You cannot call methods from objects that are null in C # /. NET (I do this in C ++, it just does not have access to any vars member)
  • Extension methods did not exist in .NET 2.0
  • Microsoft did not bother to update the standards and probably felt that it was insignificant.
+6
string c #
source share
6 answers

If IsNullOrEmpty was an instance method, calling it in a null instance will throw a NullReferenceException, rather than returning false as you would like.

It may be an extension method, but then it can be confusing - it will look like an instance method, but will not act as one.

+25
source share

If str is NULL, it will not have any access methods available because the object instance is missing. You would get a null-reference exception for trying to call a method on a null object.

String.IsNullOrEmpty is static, so it will always be available for testing string objects.

I think you could argue that it would be convenient to have str.IsEmpty (as Jonathan said, you can do

+9
source share

String.IsNullOrEmpty is a class method.

If str was Nothing (Null), you could not call the method on it. You can call the instance method on an object only.

+5
source share

IsNullOrEmpty - static method of the string class; This is not an instance method. This is because if str is null , it makes no sense to call the instance method since you will get a NullReferenceException . Thus, IsNullOrEmpty should be a static method.

+4
source share

I have been using the extension method for a while. It works great.

  public static bool IsNullOrEmpty(this string val) { return string.IsNullOrEmpty(val); } 

It obviously does the same thing as string.IsNullOrEmpty (string), but it's just easier to do something like

 if(mystring.IsNullOrEmpty()) { //... do something } 
+3
source share

In some cases, it would be nice if you could define default behavior for statically typed null references. Using extension methods, in many cases this can be effectively achieved. However, there are some errors. For example, casting an object to an unrelated type is usually prohibited in .net languages, since there are no cases where such behavior would be legal at run time. On the other hand, if the object was null, it could be passed to the object, and then the null object could be transferred to another type. If the result of such a cast can be considered the default instance of the latter type, the effect will be to make the cast semi-legal.

0
source share

All Articles