Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of a static method in a non-static class?

Tags:

scope

c#

static

I have trouble understanding the underlying errors with the code below:

class myClass {     public void print(string mess)     {         Console.WriteLine(mess);     } }  class myOtherClass {     public static void print(string mess)     {         Console.WriteLine(mess);     } }  public static class Test {     public static void Main()     {         myClass mc = new myClass();         mc.print("hello");          myOtherClass moc = new myOtherClass();         moc.print("vhhhat?");         //This says I can't access static method in non static context, but am I not?      } } 

I can't ever think of a reason why one would declare a static method in a non-static class, so why will .NET not throw an exception error.

Furthermore,

moc.print("vhhhat?"); 

This will say I can't access static method in non static context but Test and main are static, what is it referring to ?

like image 326
Matt Avatar asked Jul 24 '09 19:07

Matt


People also ask

Can static method be used in non-static class?

Static methods can be called without creating an object. You cannot call static methods using an object of the non-static class. The static methods can only call other static methods and access static members. You cannot access non-static members of the class in the static methods.

What is the point of static methods?

Static methods can be accessed without having to create a new object. A static method can only use and call other static methods or static data members. It is usually used to operate on input arguments (which can always accept), perform calculation and return value.


2 Answers

A static class means that you cannot use it in a non-static context, meaning that you cannot have an object instantiation of that class and call the method. If you wanted to use your print method you would have to do:

myOtherClass.print("vhhhat?"); 

This is not static, as you created an instantiation of the class called moc:

myOtherClass moc = new myOtherClass(); 
like image 141
AlbertoPL Avatar answered Sep 20 '22 19:09

AlbertoPL


First, the error:

moc.print("vhhhat?"); 

Is trying to call a static method on an instance of the class (i.e. a non-static context). To properly call print(), you would do

myOtherClass.print("vhhhat?"); 

For the first question, there are many reasons to have static methods in a non-static class. Basically, if there is an operation associated with the class, but not with any particular instance of the class, it should be a static method. For example, String.Format() (or any of the String static methods) should not operate on string instances, but they should be associated with the String class. Therefore they are static.

like image 39
Sean Avatar answered Sep 20 '22 19:09

Sean