Languages
[Edit]
EN

C# - using statement with multiple variables

8 points
Created by:
Pearl-Hurley
559

In this short article, we would liek to show how to use using statement with multiple variables in C#.

Quick solution:

using (var stream = new FileStream("file.txt", FileMode.Open))
using (var reader = new StreamReader(stream))
//     add more usings here ...
{
    string line = reader.ReadLine();

    // ...
}

 

C# 8 example

In C# 8 we can join usings by adding coma as variables separators.

using (
    var stream = new FileStream("file.txt", FileMode.Open),
    var reader = new StreamReader(stream)
//  add more usings here ...
)
{
    string line = reader.ReadLine();

    // ...
}

 

References

  1. using statement (C# Reference) - Microsoft Docs 

Alternative titles

  1. C# - combine multiple using statements
  2. C# - join multiple using statements
  3. C# - combine multiple usings
  4. C# - join multiple usings
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join