Solved

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

Posted on 2009-05-04
11
1,072 Views
Last Modified: 2013-11-25
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

0
Comment
Question by:Number5ix
11 Comments
 
LVL 26

Assisted Solution

by:Anurag Thakur
Anurag Thakur earned 100 total points
ID: 24302145
>>  believe that static methods should always return the same result - is that right
No it depends on what kind of processing is happening and what all are matching the criteria at that instance of time - so the results can be different

Static and Non-Static - there will be a lot of different opinions regarding the same
Normally (for me) I use static methods which can be used in different places of the application without creating an object of the class and no state is required (state - private member variables etc)
Non-Static (private/public/protected) methods are used when an instance of the class has been created and a state is required for the processing of the methods
0
 
LVL 3

Author Comment

by:Number5ix
ID: 24302253
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 ... :)
0
 
LVL 39

Accepted Solution

by:
abel earned 400 total points
ID: 24302263
I can only second what Ragi is already telling you. It is not always as clear-cut when to use class methods (the ones you call "static", or Shared in VB) or instance methods (the ones you call "non-static").

I'm showing you these "official" names - class vs. instance methods - because those names say something about how you can use one or the other. The first, the class methods, work "on the class". That is: the work not on an instantiated object of the class:

class MyClass {
    public static void doSomethingStatic() { ... somethjing... }
}
you can and must call this using the class, not using a variable:

MyClass.doSomethingStatic();
This is a very important difference and it is the same as when Ragi explains you that a static method cannot contain state: it cannot access the internal data of the instance. In other words, the following is illegal and will not compile:

class MyClass {    // static or class method     public static void doSomethingStatic() {         this.doSomethingNonStatic();   // error    }    // non-static or instance method    public void doSomethingNonStatic() { ... something ...} }
 
That is, because the second method, the instance or non-static method, actually needs an instance of the class, i.e. an object, aka. as a "new variable", to be able to work:

MyClass mc = new MyClass();  // must instantiate
mc.doSomethingNonStatic();
Now, as long as "mc" lives, which is as long as it does not go out of scope or does not have any references anymore, the instance methods can be used. The important rule is, and remains:
A class or static method acts on the class and does not require an instance variable, but cannot access any instance data.An instance or non-static method acts on an instance variable of that class and can access the data of the instance, i.e., it can use the "this" keyword and it can access private member variables.
When to use which is highly dependent on your requirements. But in general, you will have a fair amount of instance methods and very few class methods, if at all. The only exception is usually the ubiquitous utility class where helper methods are bundled together for easy access.

-- Abel --

0
 
LVL 39

Expert Comment

by:abel
ID: 24302275
> 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.
0
 
LVL 3

Author Comment

by:Number5ix
ID: 24302312
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!
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 39

Expert Comment

by:abel
ID: 24302318
you're welcome, glad we could be of some help :)
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24309546
>>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.
0
 
LVL 3

Author Comment

by:Number5ix
ID: 24310218
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!  :)
0
 
LVL 39

Expert Comment

by:abel
ID: 24310273
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();
    }
}
0
 
LVL 3

Author Comment

by:Number5ix
ID: 24311972
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!
0
 
LVL 39

Expert Comment

by:abel
ID: 24312030
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 --
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now