Click here to Skip to main content
15,883,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've read some conflicting information about the static modifier. First off, a video recorded by a .NET trainer recently said that the static modifier isn't used that often, which I found strange because I'm using it quite a bit. I've been working with C# code for years, but never at the level I am now, so I'm wondering if maybe I'm using it wrong.

Can the methods and class used to connect to SQL Server be static, even though I may be connecting to two different databases, over two different connections? No, right? That would be two instances of the class, right?

Static classes require fewer keystrokes and so I love them. However, piling on two many extension methods in a class library can make the context menu confusing.

Any input would be great.

What I have tried:

My database connection methods are instance methods, which requires the use of MyObj dbobj = new MyOb();
Posted
Updated 22-Dec-17 9:47am

1 solution

In the case of DB connections (and Commands, Adaptors and such like) these should be instances: because they should be Disposed as soon as possible to ensure they don't "linger" and mess things up later (they are scarce resources, so they should be released properly.
The easiest way to do that is via using blocks:
C#
using (MyObj dbObj = new MyObj())
   {
   ... use it here ...
   } ... destroyed when it goes out of context.

Static isn't used that much - I use it when I need data that is common to all instances, and for methods that don't need instance data.

I suspect the video trainer was overgeneralising: but I only use extension methods when I'm expanding existing sealed classes - string for example - for classes "I control" I'd use instance methods. The "less typing" bit is generally untrue, as most of the time a static method needs the class name for the call as well as teh method name - just like an non-static method needs the instance variable name.
 
Share this answer
 
Comments
[no name] 23-Dec-17 1:09am    
Than you for confirming the bit about static classes not being used that much. The less typing part is because I created a class library which I have shared across a bunch of Visual Studio projects. I should point out that I was a classic ASP/VBS web developer 10 years, went into data services for 8 years, so I'm having to learn how things are done in an object oriented environment.

All of my database calls are already using using, so I'm good there. I'm just having to remind myself that I need to ask these questions so that I don't continue with bad habits moving forward. Thanks for your time!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900