Answered A quest for key points about OracleCommand class.

satya_prakash_nandy

New member
Joined
Sep 29, 2019
Messages
2
Programming Experience
Beginner
Hello everyone, I am just a beginner in this vast c# world. Hence I want to know why most of the code over the internet had using keyword while creating a new OracleCommand object. Is there is any significant importance?
Apart from that I also want to know how to open and dispose of database connectivity efficiently in c#.
Screenshot (168).png
 
Firstly, please don't post pictures of code. We can't copy and paste it if we want to run it for ourselves in that case. Copy the code from the IDE directly if possible and then post it into the code formatting window, so that it will be syntax-highlighted and maintain indenting.

As for the question, the using keyword creates an object within the specified scope that will be disposed at the end of the block. Disposing objects is how managed code releases resources so it should always be done as soon as possible, which means as soon as you are finished using that object. Not all objects can be disposed because not all objects hold resources that need to be released. Generally speaking, any object that does will implement the IDisposable interface and any such object should have its Dispose or, if it has one, Close method called when the object is no longer required. The using block will implicitly call that method at the end of the block. If you need to create an object in one method and then use it in another then a using block is not an option but anything that is created and used only within a narrow scope should be created that way. If in doubt, read the documentation for a type and that will tell you whether it implements the IDisposable interface or you can just create a using block and the compiler will tell you if it's not valid.

Generally speaking, all data access objects should be created and destroyed only where you need them, e.g. don't create a connection and open it and then leave it open for the life of the application. If you're just retrieving data then create and destroy the connection where you execute the query. If you want to retrieve and save data either side of editing then you'll need to keep the connection around a bit longer, but you still don't keep it open. My code examples here may be of use to you. Keep in mind that, ideally, the actual data access code should not be written in a form or page so that presentation code is kept separate from business logic and data access. Pretty much everyone starts out doing it that way though, so there's nothing wrong with learning the basics that way and then learning separation of concerns later.
 

Latest posts

Back
Top Bottom