USING - C# Key word

I've been asking a question about this key word on every interview. Most of them think that this is used only to reference the base class, apart of that, there is also a great usage with this key word. This key word, USING, can be used to destroy the objects (automatically) when they are no longer required in the memory.

At times, the developer will forget to write the code to destroy the created objects. These objects pile up on system memory and wait for the GC to collect and clean them. How it would be if they are cleanned as soon they finish their requirement? That would be great coding and you are reducing the work for GC during the collection process.

Here is how to accomplish the same. First, implement the IDisposable interface on the object that you are planning to implement automatic collection and allow CLR to release the allocated memory as soon this object is no longer required.

class SmpCls: IDisposable
{
void IDisposable.Dispose()
{
Console.WriteLine("Disposing the object and cleaning");
}
public string RetHelo()
{
return "Hello World!! Happy coding ..";
}
}

While creating the object out of this class do the following way. Implement the object in the following code.

using (SmpCls obj as new SmpCls())
{
.....
.....
}

One advantage by doing this is you never required to worry about GC active, clean and clear the heap .. blah, blah ..

What are your comments

Comments

Popular posts from this blog

Network Intrusion Detection using Supervised ML technique

Common mistakes by Interviewer

Keep the system active, to avoid the auto lock