User kokos answered the wonderful Hidden Features of C# question by mentioning the using
keyword. Can you elaborate on that? What are the uses of using
?
The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.
In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.
With the C# 8.0 update, Microsoft has introduced the using declaration feature. This feature allows us to declare a disposable object with the keyword using so the object will be disposed of when it goes out of the scope.
What is the @ symbol in front of variables in C#? From the C# documentation it states that the @ symbol is an Identifier. The prefix “@” enables the use of keywords as identifiers, which is useful when interfacing with other programming languages.
The reason for the using
statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts
using (MyResource myRes = new MyResource()) { myRes.DoSomething(); }
to
{ // Limits scope of myRes MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes != null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); } }
C# 8 introduces a new syntax, named "using declarations":
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
So the equivalent code of above would be:
using var myRes = new MyResource(); myRes.DoSomething();
And when control leaves the containing scope (usually a method, but it can also be a code block), myRes
will be disposed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With