Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C#: What is the difference between "public void" and "public static void"? Thank you!?

2 Answers

Relevance
  • Chris
    Lv 7
    7 years ago
    Favorite Answer

    A static function is meant for general use and does not require an instance, while a non-static function is called on an object instance created using the class as blueprint.

    Say you have a Rectangle class. A method that calculates the area would be non-static, since you would call it on a rectangle instance: myRect.getArea(), myOtherRect.getArea(), etc.

    If you want to calculate the total area of all rectangles, it does not make sense to implement this method as part of a specific rectangle, it's a general method that should be part of the Rectangle class itself. Therefore you'd use static in its definition, and from the outside, call it using Rectangle.getTotalArea()

  • Anonymous
    7 years ago

    void = a function/method that returns nothing.

    public = to be able to be accessed anywhere in the code.

    static = to be able to be accessed without any object, just by using class name and dot operator

    so,

    public void = any method or function ( user defined or class member ) that can be accessed anywhere in the program and it won't return a value. ( if member of the class, then by using . operator after object , if user defined, then by calling simply)

    public static void = any method or function "of a class" that can be accessed without any object of that class.

    see ,

    /********************************************************************/

    public void ( example ):

    class abc {

    public void show() {

    Console.writeLine("hello");

    }

    }

    in main, to access this function you will have to create an object

    abc object;

    object.show(); // calling function with the object of that class

    /*****************************************************************************/

    user defined public void function (example)

    public void show() {

    Console.WriteLine("hello");

    }

    int main , you can call it as

    show();

    since it's a user defined function. ( you can also add parameters and other stuff if you want 0

    }

    /************************************************************************/

    public static void ( example ):

    class abc {

    public static void show() {

    Console.writeLine("hello");

    }

    }

    in main, you can call it just by class name and dot operator

    abc.show(); // calling function with just class name and dot operator

Still have questions? Get your answers by asking now.