Reputation: 41
So, when you're calling a method, how do you know when to reference the object, and how do you know when to reference the class? For example:
Why is it
String.IsNullOrEmpty(myStr);
and not
myStr.IsNullOrEmpty();
Upvotes: 1
Views: 82
Reputation: 19149
how do you know when to reference the object, and how do you know when to reference the class?
by looking at method declaration. if instance method is declared (a normal method) you should call method in this way.
myStr.IsNullOrEmpty();
if static method is declared (method signature contains static
keyword) you should call method in this way.
String.IsNullOrEmpty(myStr);
where String
is name of class and IsNullOrEmpty
is name of static method inside that class.
sometimes static methods are declared as extension methods (first parameter of static method is prefixed with this
keyword) so you can call them in two identical ways.
String.IsNullOrEmpty(myStr);
myStr.IsNullOrEmpty();
assuming IsNullOrEmpty
is extension method, both syntaxes will work perfectly fine and are identical (note that such method does not exist in .Net framework but you can write your own).
Upvotes: 1
Reputation: 51643
static methods do not need an instance of the class to be performed with, IsNullOrEmpty() is such a one -you prefix it with the classname.
Some static methods (Extensions) can be used to extend classes which you did not write and "add onto" the Methods usable with a class.
Example
// must be a top lvl class to enable declaring extension method
public static class StringExt
{
public static bool IsSet(this string s)
=> s != null && s.Trim().Length > 0;
}
Which then will be callable by if ("blablubb".IsSet()) ...
or by if (StringExt.IsSet("blablubb")) ...
.
So the short answer would be read the API (sometimes shortened to RTFM) and look at the signatures.
string.IsNullOrEmpty()
is no Extension method, its simply a static method that has no dependencys on using the string instances internal data - so it was declared static on the string class - something alike to
public static bool IsNullOrEmpty(string s)
{
// look up implementation here:
// http://referencesource.microsoft.com/#mscorlib/system/string.cs
}
Upvotes: 1
Reputation: 27653
When the method is static - reference the class.
When the method is not static - the instance.
(There are other cases such as extension methods... But I think this is what you're looking for.)
For the case you brought: See the docs under "syntax":
public static bool IsNullOrEmpty [emphasis mine]
Upvotes: 2