views:

551

answers:

4

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 it.

It sounds like you guys are saying

  1. You can't call methods from objects that are null in C#/.NET (I do it in C++, it just doesnt access any member vars)
  2. Extension methods didn't exist in .NET 2.0
  3. Microsoft didn't bother to update the standards and probably felt it was insignificant
+8  A: 

If str is null, it won't have any accessable methods, because there isn't an instance of an object. You'd 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 to test string objects.

I guess you could argue that it might be handy to have str.IsEmpty (like Jonathan said, you could make an extenion method for the string object to handle this), but really it's just as easy to call String.IsNullOrEmpty(str) and covers both situations. Even though they are not the same, most people equate them to be so (in terms of business logic and verify a value exists for a string I mean) when handling values of strings.

Kevin
+4  A: 

IsNullOrEmpty is a static method on the string class; it is not an instance method. This is because if str is null it does not make sense to invoke an instance method as you would get a NullReferenceException. Thus, IsNullOrEmpty must be a static method.

Jason
+22  A: 

If IsNullOrEmpty were an instance method, calling it on a null instance would throw a NullReferenceException, not return false like you'd want.

It could be an extension method, but then it'd potentially be confusing -- it'd look like an instance method, but wouldn't act like one.

Jonathan
It could not be an extension method; it existed before C# 3.0.
Jason
@Jason, I think what he is saying is that you could make an extension method to handle that.
Kevin
Also, don't you want `IsNullOrEmpty` to return `true` when receiving a `null` instance of `string`?
Jason
Remember the good ole days in C++ where you could do stuff like bool IsNullOrEmpty(){ if(this == null) return true etc.
dkackman
i think more correct answers are below. `IsNullOrEmpty` is a static method on the class `String`.
Jason
A simpler way to put it is that if it was an instance method, it would be `IsEmpty`, because it's too late to check for `null` at that point.
R. Bemrose
+5  A: 

String.IsNullOrEmpty is a class method.

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

mopoke
It helps to mention that it is a static method of the instance class, not just a class method. If it was a class method then what he posted would have been true ie: string someobject; someobject.isnullorempty();
JonH