-
Notifications
You must be signed in to change notification settings - Fork 56
/
UsingStatements.cs
52 lines (48 loc) · 1.49 KB
/
UsingStatements.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.IO;
namespace Disposable
{
public static class UsingStatements
{
public static void UsingUsing()
{
using (StreamReader reader = File.OpenText(@"C:\temp\File.txt"))
{
Console.WriteLine(reader.ReadToEnd());
}
}
public static void TheEffectOfUsing()
{
// The extra braces here are deliberate, and they illustrate how a using statement
// introduces its own scope, and how the variable in the using statement declaration
// is available only in that scope.
{
StreamReader reader = File.OpenText(@"C:\temp\File.txt");
try
{
Console.WriteLine(reader.ReadToEnd());
}
finally
{
if (reader != null)
{
((IDisposable)reader).Dispose();
}
}
}
}
public static void UsingDeclaration()
{
using StreamReader reader = File.OpenText(@"C:\temp\File.txt");
Console.WriteLine(reader.ReadToEnd());
}
public static void StackedUsingStatements()
{
using (Stream source = File.OpenRead(@"C:\temp\File.txt"))
using (Stream copy = File.Create(@"C:\temp\Copy.txt"))
{
source.CopyTo(copy);
}
}
}
}