What Are the Uses of "Using" in C#

What are the uses of using in C#?

The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}

to

{ // Limits scope of myRes
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes != null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
}

C# 8 introduces a new syntax, named "using declarations":

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

So the equivalent code of above would be:

using var myRes = new MyResource();
myRes.DoSomething();

And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

What is the C# Using block and why should I use it?

If the type implements IDisposable, it automatically disposes that type.

Given:

public class SomeDisposableType : IDisposable
{
...implmentation details...
}

These are equivalent:

SomeDisposableType t = new SomeDisposableType();
try {
OperateOnType(t);
}
finally {
if (t != null) {
((IDisposable)t).Dispose();
}
}

using (SomeDisposableType u = new SomeDisposableType()) {
OperateOnType(u);
}

The second is easier to read and maintain.


Since C# 8 there is a new syntax for using that may make for more readable code:

using var x = new SomeDisposableType();

It doesn't have a { } block of its own and the scope of the using is from the point of declaration to the end of the block it is declared in. It means you can avoid stuff like:

string x = null;
using(var someReader = ...)
{
x = someReader.Read();
}

And have this:

using var someReader = ...;
string x = someReader.Read();

The reason we use using statement in the following code?

1) The reason for the using statement is to ensure that the myEntities.Dispose() method is called as soon as the code inside the using statement completes. This is necessary since the PlanetWroxEntities class' base class is a DbContext which holds a connection to the database.

Database connections are a precious resource that are obtained from the database connection pool and there are only a finite number of connections available that your whole application must share. If you don't call Dispose on the myEntities object as soon as you are done with it via the using statement (or some other manner) then the myEntities object will continue to tie up that database connection for some undetermined amount of time until the garbage collection code from the .net memory manager gets around to reclaiming the memory that is held by the myEntities object that is no longer in use.

The memory manager will at that time calls the dispose method. As soon as the Dispose method is called the database connection is released from the object and returned to the database connection pool where it can be obtained by other parts of your application when you make a call to get a database connection (for example when you create other instances of the PlanetWroxEntities class.)

The purpose of the using statement is to have the Dispose method called as soon as you are done with the object so that in this case the database connection is returned to the pool right away.

2) It means the database connection is released by your application and is returned to the database connection pool where it is now available to be obtained by other parts of your application. Here is one resource that talks more about connection pooling, it will give you more background on what is going on under the hood: https://msdn.microsoft.com/en-us/library/8xx3tyca.aspx

Under the hood the using statement is implemented as a finally statement. So this code:

using (PlanetWroxEntities myEntities = new PlanetWroxEntities())    
{
var authorizedReviews = from review in myEntities.Reviews
where review.Authorized == true
orderby review.CreateDateTime descending
select review;

GridView1.DataSource = authorizedReviews.ToList();

GridView1.DataBind();
}

becomes

PlanetWroxEntities myEntities; 
try{
myEntities = new PlanetWroxEntities();
var authorizedReviews = from review in myEntities.Reviews
where review.Authorized == true
orderby review.CreateDateTime descending
select review;

GridView1.DataSource = authorizedReviews.ToList();

GridView1.DataBind();

} finally{
myEntities.Dispose();
}

In the old days of C# we always had to write the finally statement ourselves to dispose of disposable objects so that their unmanaged resources were released. But later the using statement was introduced in C# to make it easier to accomplish this. Even today, you can write the finally statement yourself if you prefer, but most people love the using statement.

For more information see https://msdn.microsoft.com/en-us/library/yh598w02.aspx

Using the using statement in C#

The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.

    //the compiler will create a local variable 
//which will go out of scope outside this context
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}

Alternatively you could just use:

    FileStream fs;
try{
fs = new FileStream();
//do Stuff
}
finally{
if(fs!=null)
fs.Dispose();
}

Extra reading from MSDN

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

What does using System mean in C#?

The using System line means that you are using the System library in your project. Which gives you some useful classes and functions like Console class or the WriteLine function/method.

The namespace ProjectName is something that identifies and encapsulates your code within that namespace. It's like package in Java. This is handy for organizing your codes.

class Program is the class name of your entry-point class. Unlike Java, which requires you to name it Main, you can name it whatever in C#.

And the static void Main(string[] args) is the entry-point method of your program. This method gets called before anything of your program.

And you can actually write a program without some of them in DotNet 5 and later as it now supports top level functions.

use of using keyword in c#

Two uses:

  • Using directives, e.g.

    using System;
    using System.IO;
    using WinForms = global::System.Windows.Forms;
    using WinButton = WinForms::Button;

    These are used to import namespaces (or create aliases for namespaces or types). These go at the top of the file, before any declarations.

  • Using statements e.g.

    using (Stream input = File.OpenRead(filename))
    {
    ...
    }

    This can only be used with types that implement IDisposable, and is syntactic sugar for a try/finally block which calls Dispose in the finally block. This is used to simplify resource management.

When should I use using blocks in C#?

When the SomeType class implements IDisposable.

Explain using statement in C# code in middle of code... (not in header as loading libraries)

using is used in conjunction with types that implement the IDisposable interface.

It ensures that when the object is out of scope, the Dispose method is called (as defined in IDisposable) and is often used to dispose of unmanaged resources.

Your first example is a traditional using block, where the object scope is defined by the following {}.

Your second is a new using statement, introduced in C#8, where the scope is the enclosing block, as with other local variables.

It is roughly equivalent to:

var font1 = new Font("Arial", 10.0f);
byte charset = font1.GdiCharSet;
font1.Dispose();

But as pointed out by Casey, it actually ensures the object is disposed of, even if an exception is thrown inside the block i.e.

var font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
{
font1.Dispose();
}
}

C# USING keyword - when and when not to use it?

No, IDisposable items are not disposed when they go out of scope. It is for precisely this reason that we need IDisposable - for deterministic cleanup.

They will eventually get garbage collected, and if there is a finalizer it will (maybe) be called - but that could be a long time in the future (not good for connection pools etc). Garbage collection is dependent on memory pressure - if nothing wants extra memory, there is no need to run a GC cycle.

Interestingly (perhaps) there are some cases where "using" is a pain - when the offending class throws an exception on Dispose() sometimes. WCF is an offender of this. I have discussed this topic (with a simple workaround) here.

Basically - if the class implements IDisposable, and you own an instance (i.e. you created it or whatever), it is your job to ensure that it gets disposed. That might mean via "using", or it might mean passing it to another piece of code that assumes responsibility.

I've actually seen debug code of the type:

#if DEBUG
~Foo() {
// complain loudly that smoebody forgot to dispose...
}
#endif

(where the Dispose calls GC.SuppressFinalize)



Related Topics



Leave a reply



Submit