Static vs. non-static method

前端 未结 10 1109
执念已碎
执念已碎 2020-11-28 08:30

Suppose you have some method that could be made static, inside a non-static class.
For example:

private double power(double a, double b)
    {
        r         


        
10条回答
  •  难免孤独
    2020-11-28 09:25

    i hope we need to define the difference between static and non-static method. Here i am posting few easy lines of code to visualize the conceptual difference.

    public class StaticVsNonStatic
    {
         public string NonStaticMethod() //non-static
         {
    
             return "I am the Non-Static Method"; 
    
         }
    
         static public string StaticMethod() //static
         {
    
             return "I am Static Method";
         }
    
     }
    

    Now lets create an aspx page try to access these 2 methods defined in the class.

     public partial class StaticVsNonStatic_StaticVsNonWorkplace : System.Web.UI.Page
     {
         protected void Page_Load(object sender, EventArgs e)
         {
    
            StaticVsNonStatic objStaticVsNonStatic = new StaticVsNonStatic();
            lblDisplayNS.Text = objStaticVsNonStatic.NonStaticMethod(); //Non Static 
            lblDisplayS.Text =  StaticVsNonStatic.StaticMethod();  //Static and called without object
         }
     }
    

    Thanks and please post you comments.

    Best Regards, Pritom Nandy [Bangladesh]

提交回复
热议问题