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,315
  • 11
  • 23

1 Answers1

3

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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#example

Nicklaus Brain
  • 884
  • 6
  • 15