Using Statement

With a using statement you indicates that the instantiated object is just available within the using statement, say within the brackets. If the code is passed the brackets the instantiated object is  is disposed and memory is cleared.

Rule of thumb is:

every object which inherits from IDisposable must be used with a using statement.

Example:

using ( system.data.sqlclient.sqlcommand sqlcmd)
   {

   }

So, within the brackets the SqlCommand is available, outside the brackets the object is disposed and memory is cleared.

If you want to build you own objects wich can be used with a using statement then you have to inherit your object from IDisposable AND implement the Interface.

Example:

public class mijnClass: Idisposable
{
    public mijnClass();
}

C#8

Notation of the using statement is enhanced. No braces needed anymore:
Example

static int WriteLinesToFile(IEnumerable lines)
{
    using var file = new System.IO.StreamWriter("WriteLines2.txt");
    // Notice how we declare skippedLines after the using statement.
    int skippedLines = 0;
    foreach (string line in lines)
    {
        if (!line.Contains("Second"))
        {
            file.WriteLine(line);
        }
        else
        {
            skippedLines++;
        }
    }
    // Notice how skippedLines is in scope here.
    return skippedLines;
    // file is disposed here
}

Meaning that the file is disposed at the end of the method. Most of the time this is wat happens in a method. So like this less brackets are needed and results in more readable code!

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!