CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Apr 2011
    Posts
    58

    Just when I thought I fully understood static vs non-static methods...

    I was looking through a program I am working on, and my Form1 class has several methods that are NOT static, but I call them like they are static.

    Code:
    public partial class Form1 : Form
    {
      public Form1()
      {
        //constructor
        DoSomething();
      }
    
      private void DoSomething()
      {
      }
    }
    since DoSomething is not static, I thought it would need an object reference, such as this.DoSomething()???

    But this does compile and run, so I am confused.

    What did I miss when I was studying static methods?

    Skip
    Last edited by MrGibbage; August 10th, 2011 at 09:48 AM.

  2. #2
    Join Date
    May 2007
    Posts
    1,546

    Re: Just when I thought I fully understood static vs non-static methods...

    "this." is implicit. If you call a method it's assumed you're calling one on the current object unless explicitly told otherwise.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  3. #3
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Just when I thought I fully understood static vs non-static methods...

    Like Mutant said, the 'this' reference is an implicit parameter to every instance method. It is the same as calling this.DoSomething().

  4. #4
    Join Date
    Apr 2011
    Posts
    58

    Re: Just when I thought I fully understood static vs non-static methods...

    I understand that the "this." can be implicit, but what about the "static"? My method, "DoSomething" is not declared as static. I thought non-static was implied unless static was declared.

    I'm still missing something.

  5. #5
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Just when I thought I fully understood static vs non-static methods...

    Right, it's not static... I'm not sure what you're asking exactly. It is a non-static instance method. When you call an instance method from within a class 'this' is implicit.

  6. #6
    Join Date
    Apr 2011
    Posts
    58

    Re: Just when I thought I fully understood static vs non-static methods...

    *sigh* I figured it out.

    I had one method in my Form1 class that I had accidentally declared as static. When I tried calling another non-static function in the class, the autocomplete wouldn't fill in the method name, and if I typed it in myself, I got a warning that it needed to be called with an object. Since I didn't realize at the time that I was in a static method, I immediately assumed that I needed to declare that second method as static. Well, that helped until I saw that all the rest of my functions were not static.

    I understand that you cannot call a non-static method from a static method because there is no "this."

    I'm all good now, and thank you all for bearing with me in my senior moment.

    *sigh*

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Just when I thought I fully understood static vs non-static methods...

    As you know, "this." is implicit because you are operating within the context of an instance of the class.

    That being said, you can declare any methods as static that don't manipulate instance data. So as long as a method operates only on passed in data and not on class fields or properties or other non-static methods, you can declare the method as static.

    For what it's worth, tools such as Resharper will recommend making methods static whenever possible. So if your method only acts on passed in data, it will recommend that you make the method static.

  8. #8
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Just when I thought I fully understood static vs non-static methods...

    Quote Originally Posted by MrGibbage View Post
    I understand that you cannot call a non-static method from a static method because there is no "this."
    As static methods semantically belong to the class itself, and not to it's individual instances (in fact, VB.NET equivalent to static is Shared, implying that all the objects of that class share the class member), you cannot call a non-static method (instance method) without an instance to call it on.

    Code:
    public static void DoSomething()
    {
        SayHello();        // Compiler error 1
    
        // or
    
        this.SayHello();    // Compiler error 2
    }
    
    public void SayHello()
    {
        PlaySound("hello.mp3");
    }
    Compiler:
    (1) Who are you talking to?
    (2) Who is "this"? Did you hit your head or something???


    However, if you pass an instance of that class to the static method, you can use it to call it's non-static, instance-specific methods all you like.
    Even the private ones, since protection levels in C# pertain to the class and not to the object.

    Code:
    public static void DoSomething(Chatty aChatty)
    {
       aChatty.SayHello();    
    }
    Compiler: Now I get it!

    P.S. This is how, among other things, custom operators are often implemented.
    Last edited by TheGreatCthulhu; August 10th, 2011 at 07:13 PM. Reason: Eeek! I forgot to put "void" everywhere!

  9. #9
    Join Date
    Apr 2011
    Posts
    58

    Re: Just when I thought I fully understood static vs non-static methods...

    This is really clearing things up for me. Somehow I got the notion in my head that static methods should be kept to a minimum, because it doesn't follow standard OOP practices. I think the real answer is make a method static when it needs to be static. In other words, do the right thing.

  10. #10
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Just when I thought I fully understood static vs non-static methods...

    Quote Originally Posted by MrGibbage View Post
    I think the real answer is make a method static when it needs to be static. In other words, do the right thing.
    Yeah, but the trick is to know when a method needs to, or could be static. This somewhat depends on your personal preferences, however, making most of your methods static can turn your OO language into a procedural one - which completely defeats the purpose of the language being OO in the first place. It is possible to use C# to write what is essentially a procedural program, by making all of your methods static, never using writing classes or structs, and calling everything from main. But, that is not very fun...

    Basically, it comes down to experience. The .NET library itself is a good reference - whenever you stumble upon a static method, think about why they made it as such.

    In a nutshell, instance methods generally use, or modify, instance-specific data (the data belonging to the same object they belong to). They can operate on some external data at the same time, passed to them via method parameters. For example, if you had a Person class, and methods called SetFirstName(), GetLastName(), SetBirthDate(), CalculateAge() - all of these work on a specific person instance, and on instance specific data.

    However, as a design choice, you can pick some of these methods and make them static - make them some sort of utility methods of the Person class. Like:
    int age = Person.CalculateAge(methuselah); // where methuselah is a Person instance

    So, what kind of methods are usually static?
    Well, there are the aforementioned utility methods. Take the Math class, provided by the framework: all of it's methods represent math operations and are static, as is the Math class itself (static, that is): Math serves to group these related methods.

    Or take look at the Point struct (System.Drawing namespace): it has several static methods, among them Round(), that takes a PointF (a point based on floats), rounds x & y, and returns a new instance of Point (a point based on integers).
    Point location = Point.Round(floatLocation);

    This method makes more sense as static. If it was an instance method, it would imply that the specific point instance should somehow be rounded after a call to this method - but, what is "Round" supposed to mean for integers?

    This is also a method that constructs a new instance of it's class. A lot of static methods serve as an alternate way to construct objects. For example, the Bitmap class has several constructors, but it also has two static methods (called FromHicon & FromResource) used to construct a bitmap from an unmanaged resource. They could have been made into constructors, but the designers chose to make them this way.
    The Color struct has a similar, often used static method FromArgb(), that let's you create a Color instance by providing ARGB color components.

    Also, some design patterns, like Singleton, utilize static methods to construct objects.

    But, make no mistake - most of the methods you write or work with will be instance methods.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured