Home > Net >  What is the benefit of using a static method over a normal method without a class?
What is the benefit of using a static method over a normal method without a class?

Time:06-06

im pretty new to C# and i was a little confused about the use of static methods over regular methods. From what i understand, the only benefit they offer is that they require no object in order to be called. But if thats the case, wouldn't it just be more convenient not to assign this method to a class and to define it in the main program page. Is there any real benefit to static methods?

Edit: What i mean by "wouldn't it be more convenient not to assign this method to a class" is to not create a seperate class where i can put this new method in. Wouldn't it just be more convenient to keep this method in the main program's class.

CodePudding user response:

If you define it in the "main program page" it wouldn't be as easy to use throughout the application, it would only be available from that 1 file.

Imagine you have a static class MyStaticClass, you could then use those functions throughout the application, not only on the main program file, but in any file, etc.

MyStaticClass.MyStaticMethod();

in a standard class you would have to do something like

new MyClass().MyMethod();

in other words the reason for a "static" is that you do not have to "new" an instance of the object.

  •  Tags:  
  • c#
  • Related