Link to home
Start Free TrialLog in
Avatar of Number5ix
Number5ixFlag for Australia

asked on

C# - Static vs non-static classes & methods - some clarification please?

Hi all,

I'm not a professional developer so please excuse my lack of knowledge here ... got a question or 2 for y'all though.

The code sample below is a simple method that obviously returns the result of an identical service method (repository design pattern).  As you can see, it's static.  The method is from a Windows Forms application and in the example it's from the method won't ever be called more than once at a time.  I believe that static methods should always return the same result - is that right?

Why should this method be static/non-static?  If it's only being called from one class at a time does it matter?  The class that contains the method below doesn't get instantiated either - it doesn't need to, I think.

Can someone please explain this if you understand what I'm asking?

Thanks!
public static IList<Application> ListAllApplications(string connStr)
{
   return ApplicationService.ListAllApplications(connStr);
}

Open in new window

SOLUTION
Avatar of Anurag Thakur
Anurag Thakur
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Number5ix

ASKER

Hi there,

Thanks for your comment.  So, if I have a static method, it gets used but its class hasn't been instantiated and a private member variable gets set there is a chance of that variable getting overwritten if that method gets called again without the class being instantiated?

Is the simple solution just to make sure that you instantiate an instance of the class every time before calling the method and make the methods non-static?

Sorry if I've messed up my terminology there ... :)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> So, if I have a static method, it gets used but its class hasn't been instantiated
> and a private member variable gets set there is a chance of that variable
>  getting overwritten if that method gets called again without the class being instantiated?

no, a static vs non-static method can never overwrite one another. A static method cannot be used from an instance of the class, and a non-static method cannot be used without an instance of the class.

> Is the simple solution just to make sure that you instantiate an instance
> of the class every time before calling the method and make the methods non-static?

you need an instance of the class when you want to use instance methods, i.e., non-static methods. You never need an instance of the class if you need access to static methods.
I'm splitting the points because of the extremely fast response from ragi0017 and because of the completeless of the answers provided by abel.

I hope you don't mind this split - the answers, combined, answered my questions perfectly.

Thanks again!
you're welcome, glad we could be of some help :)
>>A static method cannot be used from an instance of the class

To clarify:

mc.DoSomethingStatic();  will not compile.

However, DoSomethingNonStatic CAN call DoSomethingStatic();  So your instance can reference the static members.
Hmmm thanks DanielWilson - I'll have to do some tests on that.  Thanks for your comment & sorry you were too late to claim any of the points!  :)
what danielwilson means, I think, is that inside any instance method, whether that is on your current class, or on an alien class, you can access the static methods (the second method shows calling a static method from an instance method, the last method below does the reverse, which actually cannot be done, but creating a new object is of course possible as it would be possible in any other method):

class StaticTests
{
    // needs a public ctor to be instantiatable
    public StaticTests() {}

    public static int getSomeIntStatic()
    {
        return (10);
    }

    public void doSomethingNonStatic()
    {
        // works:
        int localValue = StaticTests.getSomeIntStatic();    

        // works not
        int localValue = this.getSomeIntStatic();    // error
     }

    public static void doSomethingElseStatic()
    {
         // you cannot use the this-pointer, but you can instantiate a new object and use that
         StaticTests localST = new StaticTests();
         localST.doSomethingNonStatic();
    }
}
Ok, I understand all that so far - no problem.

What I should have asked initially and probably what I should have waited for before assigning points, is when/where to use instance or class methods?  Are there any hard & fast rules that guide developers on this point?

The application in question is a simple one at the moment and it reads required information about applications and passwords from a SQL database.  It all works fine - it's a Windows Forms application and will really only be used  by one person at a time.  I've got presentation methods that interface (bad choice of word perhaps considering I'm not talking about interfaces) with the UI and which communicate with the services layer for the database processes.

Is there anything you guys consider worth passing on re when to use interface or class methods for a situation like this?  E.g. the UI displays the form, the form calls the presentation method (the original source code sample was one of the presentation methods) which then call the service methods to, for example, read information about a specific application from the database.

Any hints?  That's the part I don't understand.

Please also let me know if you'd like another question opened for that discussion as I'm happy to throw another 500 points at whoever can help me on this - I just haven't opened another one yet as the information from all participants so far has been extremely valuable.

Thanks!
Well, you asked this already in your original question, so I don't think you need to open up a new question, however, if you want more input and some others to look at it, it is probably a good idea (more so, because many experts tend to "unmonitor" themselves from answered questions).

To answer your question is not easy. In general, as was mentioned earlier here, you should only use static methods when you do not need to hold any state. Static methods are by some OO purists considered "bad design" and although that can be debated, you should be cautious in using them. They are common in certain scenarios (I mentioned utility methods earlier) but more often than not, static methods are abused because they are so easy to understand and so close to the procedural programming style (which is why they are considered "bad design" in the first place).

As soon as you find yourself writing static methods where you pass on some information from method to method (i.e., the id of a person, the current event, the db object) or you find yourself creating global objects that you are accessing from your static methods (i.e., session variables through Current HttpSession, global Dictionary objects or just other global statics that you need to call to get data), you are on the wrong track and you should probably switch to instance methods.

Turning this around and put more simply: you need instance methods unless you have a (very) good reason not to use instance methods.

-- Abel --