C# using statement – C# Programming Example
C# General

C# using statement

Many programmers have the problem that they do not know when and how to release an object.
When is it useful to use .Close () and when to use .Dispose ()? Or maybe you prefer both?

Exactly for this case the framework provided the Using command. To use Using, the object must have implemented the IDispose interface.

Provides a convenient syntax that ensures the correct use of IDisposable objects.

Example

The following example shows how to use the using statement.

As you can see here, the StreamReader is available in the Using block, as soon as the Using block is exited, the framework cleans up the object so that the GarbageCollector can do its job.

C# using statement multiple

Multiple instances of a type can be declared in the using statement, as shown in the following example:

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: