1

Hi I was going through some examples in C# and came across some code similar to below :

private void WriteData(string filePath)
{
    using var writer = new System.IO.StreamWriter(filePath);

    //Logic to write data here
}

I want to know what is the use and significance of using in variable declaration. Also how is it different from simple variable declaration :

var writer = new System.IO.StreamWriter(filePath);
Jasmeet
  • 1,239
  • 8
  • 18

1 Answers1

2

It is a C# 8 syntax sugar for a traditional using statement which ensures that Dispose() method will be called for a type implementing IDisposable interface.

See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#example

Nicklaus Brain
  • 864
  • 5
  • 15