Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which case shouldn't I use static members in a class?

Tags:

c#

.net

static

I have to ask this question because I feel that only experienced programmers can know the pros and cos of static members in a class. I've read books explaining about static members, I've also used many static members in my project according to my points of view.

As I understand, if there is some class which is used only 1 time in my project, I mean there is no need to create some or many instances, I should make all its members static, especially static methods. Is this true? This has another benefit because of that calling to static members can be done easily without creating new instances or passing instances between our classes.

Using static members in my projects doesn't show me what's wrong with it, my project seems to run normally, of course I don't mean I like using static members and use it randomly, frequently (as I explained my point of view above). I think there may be some pros and cons of static members (that I don't know) and I would like to know from your experience. Please share with me.
Thank you!

like image 991
King King Avatar asked Dec 11 '22 15:12

King King


1 Answers

Check out the following posts:

  • Why are static variables considered evil?
  • When to use static variables?
  • what is the use of static variable in c#?When to use it?why cant i declare the static variable inside Method?
  • What is use of a private static variable in Java?
  • C# Topics: Static Variables

As I understand, if there is some class which is used only 1 time in my project, I mean there is no need to create some or many instances, I should make all its members static, especially static methods. Is this true?

It depends. I believe that static classes are good if you want to access them globally throughout your application (ie, utility classes, helper functions, etc).

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

Keep in mind that declaring a class static allows it to stay in memory for the lifetime of the application. This means if the static class is only used once, it will still remain in memory even after it is not needed/will be used again. Instead, if the class is only used once, you may be better off creating a regular class instance so that GC will clean up after you're done using it.

like image 160
d.moncada Avatar answered Jan 02 '23 01:01

d.moncada