What is the difference between static methods in a static class and static methods in a static class?

I have two classes Class A and ClassB:

static class ClassA { static string SomeMethod() { return "I am a Static Method"; } } class ClassB { static string SomeMethod() { return "I am a Static Method"; } } 

I want to know what is the difference between ClassA.SomeMethod(); and ClassB.SomeMethod();

When both can be accessed without instantiating the class, why do we need to create a static class and not just use a non-static class and declare methods as static?

+37
c # oop static static-methods non-static
Mar 09 '11 at 5:50
source share
5 answers

The only difference is that static methods in a non-static class cannot be extension methods .




In other words, this is not true:

 class Test { static void getCount(this ICollection<int> collection) { return collection.Count; } } 

whereas it really is:

 static class Test { static void getCount(this ICollection<int> collection) { return collection.Count; } } 
+37
Mar 09 2018-11-11T00:
source share

A static class can contain only static members.

The static method ensures that even if you were to create several objects of class B, they would use only one, the common function SomeMethod.

Technically, there’s no difference except that ClassA SomeMethod must be static.

+14
Mar 09 2018-11-11T00:
source share
+3
Mar 09 2018-11-11T00:
source share

If you have a non-static class containing only static methods, you can instantiate this class. But you cannot use this instance meaningfully. NB: when you do not define a constructor, the compiler adds it for you.

A static class does not have a constructor, so you cannot instantiate it. Also, the compiler throws an error when you add an instance method to it (where you meant the static method).

See also documents .

+3
Sep 19 '12 at 11:30
source share

The static method belongs to the class, and the non-static method belongs to the class object. That is, a non-static method can only be called on an object of the class to which it belongs. The static method can only access static members. A non-static method can have access to both static and non-stationary elements, since at the time the static method is called, the class may not be created (if it is called by the class itself). In another case, a non-static method can only be called when the class has already been created. The static method is used by all instances of the class. Whenever a method is called in C ++ / Java / C #, an implicit argument (this link) is passed along with / without other parameters. In the case of calling the static method "this link is not passed, because static methods belong to the class and, therefore, do not have" this link ".

+1
Mar 09
source share



All Articles